2012-03-22 198 views
2

我需要关于数组插入到mysql表的帮助。PHPMySql数组插入到表

我有一个数组,当我添加和物品到购物车中

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

现在如果我有车一个项目,当我做print_r($_session['cart_array'])阵列看起来像

Array([0] => Array ([item_id] => 1 [quantity] => 1)) 

现在我需要将此阵列数据插入名为purchased_products的表,其列

id, product_name, product_quantity 

回答

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."')"); 

使用NULL,如果你的ID是自动递增。

希望它可以帮助你..

+0

谢谢你让我看看 – 2012-03-22 04:11:45

+0

好。希望它会帮助。:) – 123 2012-03-22 04:18:39

+0

谢谢。插入数据,但有一点问题.... 首先它显示未定义偏移量1,第二个概率是它插入零在item_id和数量列中每次我运行它 – 2012-03-22 04:31:08

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."')"); 

    } 

这是你想要的吗?

0

Serialize你的数组与PHP函数searialize($yourarray)和存储在数据库中。

从数据库中提取后,使用unserialize()作为实际数组。

更多详情请看这里:PHP: Using serialize to handle and store arrays

+0

将工作插入数据到三列id,product_id和product_quantity 。 我不想将数组存储为单列中的字符串.as serialize does – 2012-03-22 07:22:17

+0

没有办法将数组直接存储在数据库中。对于三列,您可以制作强制序列化的字符串并将它们存储在相应的列中。 – 2012-03-22 07:27:32

+0

好,这是我的情况下 阵列( [0] =>数组([ITEM_ID] => 1 [量] => 2) [1] =>数组([ITEM_ID] => 4 [量] = > 1) ) 我看到了教程,但这不是我的情况...任何帮助请 – 2012-03-22 07:36:00