PHP MySql数组插入表

时间:2012-03-22 03:56:13

标签: php mysql

我需要有关将数组插入mysql表的帮助。

我在购物车中添加商品时有一个数组

$_session['cart_array'] = array("item_id" => $pid, "quantity"=>1) 

现在,当我print_r($_session['cart_array'])数组看起来像

时,我在购物车中有一个项目
Array( [0] => Array ( [item_id] => 1 [quantity] => 1 ) )

现在我需要将此数组数据插入名为purchase_products且具有列

的表中
id, product_name, product_quantity 

3 个答案:

答案 0 :(得分:2)

$item_id = $_session['cart_array'] [item_id];
$quantity = $_session['cart_array'] [quantity];

然后尝试在数据库中插入该变量:

$insert = mysql_query("INSERT INTO table_name VALUES ('NULL', '".$item_id."', '".$quantity."')");

如果你的id是自动增量,请使用NULL。

希望它可以帮到你..

答案 1 :(得分:0)

对于

   $_session['cart_array'] = array(array("item_id" => 1, "quantity"=>1),array("item_id" => 2, "quantity"=>2));

    foreach($_session['cart_array'] as $key=>$val){
        mysql_query("INSERT INTO (id, product_name, product_quantity) VALUES ('".$val->item_id."','NULL',  '".$val->quantity."')");

    }

这是你想要的吗?

答案 2 :(得分:0)

Serialize您的数组使用PHP函数searialize($yourarray)并存储在数据库中。

从数据库中获取后,使用unserialize()生成实际数组。

详情请见PHP: Using serialize to handle and store arrays

相关问题