2

我已经实现了 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 变量。

乱码代码如下

$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 中,每次循环时创建一条新记录?

4

1 回答 1

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'] ."')";
}
于 2013-06-26T01:24:43.307 回答