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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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); } }
Method 2
$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);
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0