Home > Blockchain >  multiple products not saving in mysql table in codeigniter
multiple products not saving in mysql table in codeigniter

Time:10-07

i have a codeigniter shopping cart website, where user can add multiple products in cart and then checkout, when the user clicks the confirm button in checkout the user details and product details should be added to database, i did the following code:

public function checkout()            {
    
$data['items'] = array_values(unserialize($this->session->userdata('cart')));
$data['total'] = $this->total();
     
foreach ($data['items'] as $item){
 $itemname=$item['name'];
 $productid=$item['id'];
 }
    
 if(isset($_POST['confirm']))
{
  $name=$this->input->post('name');
$phone=$this->input->post('phone');
$email=$this->input->post('email');
$address=$this->input->post('address');
$productname=$itemname;
$total=$this->input->post('total');
$productid=$productid;
$this->product->addorder($name,$phone,$email,$address,$productname,$total,$productid);
}

$this->load->view('checkout', $data);
              
}

all the details are being added to the database, but there is one issue, the itemname and productid as you can see in the foreach loop, even if multiple products are there in the cart only the first product name and id is being stored in the database, i want to save all the itemname and id in the cart to database, can anyone please tell me what is wrong in here, thanks in advance

CodePudding user response:

Your Loop does only create one data, if there is multiple data, put your insert query inside looping code,

try this

if(isset($_POST['confirm']))
{
    foreach ($data['items'] as $item){
        $itemname=$item['name'];
        $productid=$item['id'];
        $name=$this->input->post('name');
        $phone=$this->input->post('phone');
        $email=$this->input->post('email');
        $address=$this->input->post('address');
        $productname=$itemname;
        $total=$this->input->post('total');
        $productid=$productid;
        
        $this->product->addorder($name,$phone,$email,$address,$productname,$total,$productid);
    }
    
}

CodePudding user response:

$itemname = array();

$productid = array();

foreach ($data['items'] as $item){

       array_push($itemname, $item['name']);

       array_push($productid, $item['id']);
 }

if(isset($_POST['confirm']))
{

$productname = json_encode($itemname);

$productid = json_encode($productid);

$this->product->addorder($name,$phone,$email,$address,$productname,$total,$productid);

}
  • Related