多个产品未在 codeigniter 中保存 mysql table

multiple products not saving in mysql table in codeigniter

我有一个 codeigniter 购物车网站,用户可以在购物车中添加多个产品然后结帐,当用户在结帐时单击确认按钮时,用户详细信息和产品详细信息应添加到数据库中,我做了以下操作代码:

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);
              
}

所有的细节都被添加到数据库中,但有一个问题,如您在 foreach 循环中看到的商品名称和产品 ID,即使购物车中有多个产品,只有第一个产品名称和 ID正在存储在数据库中,我想将购物车中的所有商品名称和 ID 保存到数据库中,谁能告诉我这里有什么问题,在此先感谢

$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);

}

你的循环只创建一个数据,如果有多个数据,把你的插入查询放在循环代码中,

试试这个

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);
    }
    
}