简体   繁体   中英

How to insert multidimensional array into database?

My array ie $_SESSION['cart_array'] contains

Array ( [0] => Array ( [item_id] => qwerty [quantity] => 2 [unit_price] => 500 ) [1] => Array ( [item_id] => skjbm [quantity] => 3 [unit_price] => 100 ) ) 

The code to insert into my database code is

 foreach($_SESSION['cart_array'] as $each_item){ $sql=mysql_query("INSERT INTO product_added(id,ip_address,order_id,email,item_id,unit_price,quantity,total,pay_status)values('','','','','".$each_item['item_id']."','".$each_item['quantity']."','".$each_item['unit_price']."','','')");
 if(!mysql_query( $sql)){
    // maybe not the best use of `die` here?
    die('Error: ' . mysql_error());
}echo "record added"; }

My problem is when I run the script it add only one item ie: item_id=qwerty,quantity=2 and unit_price=500 to the table where as I have two items in the $_SESSION['cart_array'] .

And mysql error shows:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

How to enter two and multiple items into database?

Try like this. Btw mysql is deprecated use mysqli

$insert_query = 'INSERT INTO product_added (id,ip_address,order_id,email,item_id,unit_price,quantity,total,pay_status) values ';

 foreach($_SESSION['cart_array'] as $each_item){ 

    $insert_query .= "('','','','','".$each_item['item_id']."','".$each_item['quantity']."','".$each_item['unit_price']."','',''),";        

 }

$query = rtrim($insert_query, ',');
if(!mysql_query($query)){
    die('Error: ' . mysql_error());
}else{
    echo "record added";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM