从Simplecart数组创建MySQL Insert语句

时间:2013-06-26 01:18:18

标签: php mysql simplecart

我已经实现了Simplecart,并将购物车的内容传递到另一个页面,我想将产品标识符与数量和唯一标识符一起保存到MySQL数据库表中,以便我可以提取所请求的产品和数量在那个标识符上。 Simplecart将以下信息发送到我的页面..

Array ( [currency] => USD [shipping] => 0 [tax] => 0 [taxRate] => 0 [itemCount] => 5 
[item_name_1] => ProductA [item_quantity_1] => 1 [item_options_1] => identifier: 0057 
[item_name_2] => ProductB [item_quantity_2] => 3 [item_options_2] => identifier: 0024 
[item_name_3] => ProductC [item_quantity_3] => 1 [item_options_3] => identifier: 0059 
[item_name_4] => ProductD [item_quantity_4] => 1 [item_options_4] => identifier: 0106 
[item_name_5] => ProductE [item_quantity_5] => 1 [item_options_5] => identifier: 1031 )

我拼凑了我在这里看到的各种脚本,以生成像这样打印的sql语句

insert into products values (51ca3d6e580c6,1,identifier: 0057)
insert into products values (51ca3d6e580c6,3,identifier: 0024)
insert into products values (51ca3d6e580c6,1,identifier: 0059)
insert into products values (51ca3d6e580c6,1,identifier: 0106)
insert into products values (51ca3d6e580c6,1,identifier: 1031)

这至少告诉我,我每次都创建了一个填充正确数据的循环,但是当我尝试在每次循环时插入记录时,我只得到最后一次迭代。我也不明白如何在循环中爆炸Item_Options变量。

kludged代码位于

之下
$content = $_POST;
$item_number = array();
$item = array(); 

for($i=1; $i < $content['itemCount'] + 1; $i++) 
{
$name = 'item_name_'.$i;
$quantity = 'item_quantity_'.$i;
$options = 'item_options_'.$i;
$item_number['total'] = $i;

$item[$i]['name'] = $content[$name];
$item[$i]['quantity'] = $content[$quantity];
$item[$i]['options'] = $content[$options]; 
}  

$total = $item_number['total'];
$line = 0;

while ($line <= $total -1) 
{
$line++;
$statement = $myid . "," . $item[$line]['quantity'] . "," . $item[$line]['options'];
$sql = "insert into products values ($statement)"; 

$result=mysql_query($sql);

}
mysql_close();

所以,我的问题是,如何将每个唯一ID,数量和(爆炸)标识符添加到MySQL中,每次循环时创建一条新记录?

1 个答案:

答案 0 :(得分:0)

尝试 -

while ($line <= $total -1){
    $line++;
    $statement[] = "(".$myid . "," . $item[$line]['quantity'] . "," . $item[$line]['options'].")";
}

$sql = "insert into products values ".implode(",",$statement);
$result=mysql_query($sql)

这将创建一个$statement数组,其值为

(id,qty,product)

然后在implode()查询变为 -

insert into products values (id,qty,product),(id,qty,product),...

修改

根据你的编辑,尝试 -

for($i=1; $i < $content['itemCount'] + 1; $i++){
    $quantity = 'item_quantity_'.$i;
    $options = 'item_options_'.$i;
    $item_number['total'] = $i;

    $exploded = explode(' ', $content[$options]);  // need to use the $content[] here
    $item_id = $exploded[1];

    $item[$i]['quantity'] = $content[$quantity];
    $item[$i]['options'] = $item_id;   // use the exploded value, not the $content[]
}  

$total = $item_number['total'];
$line = 0;

while ($line <= $total -1){
    $line++;
    $statement[] = "('".$myid . "','" . $item[$line]['quantity'] . "','" . $item[$line]['options'] ."')";
}