0

我有这样的表项:

id_item       color           stock
1         red,green,yellow   10,20,30

这里有一个餐桌推车:

id id_trans     id_item    color    qty
1     123          1           red      5   
2     123          1           green    2  

我想要实现的是更新表项变成这样:

id_item       color           stock
1         red,green,yellow   5,18,30

我要做的是:

$query = mysql_query("select a.color as color, a.stock as stock, b.id_item as id_item,b.color as colors,b.qty as qty from item as a, cart as b where a.id_item = b.id_item and b.id_trans = '123' ");
while($result = mysql_fetch_array($query)){

$colors = $result['colors'];
$color = explode(",",$result['color']);
$stock = explode(",",$result['stock']);
$flag = array_search($colors,$color);
$stock[$flag] = $stock[$flag] - $result['qty'];
$stock = implode(',',$stock);

mysql_query("update item set stock = '$stock' where id_item = '$result[id_item]'");

}

从我上面写的代码,我有一些问题。我的问题是,结果是这样的:5,20,30 & 10,18,30。所以,当我更新到表格项目时,它只是像这样改变:

id_item       color           stock
1         red,green,yellow   10,18,30

我想要实现的是将股票内爆为 5、18、30。谁能告诉我如何实现这一目标,或者谁能告诉我我的代码有问题?谢谢

4

1 回答 1

1

现在它比您之前的尝试更清晰;)试试这个,看看它是否有效:

unset($color);unset($stock);
$query = mysql_query("select a.color as color, a.stock as stock, b.id_item as id_item,b.color as colors,b.qty as qty from item as a, cart as b where a.id_item = b.id_item and b.id_trans = '123' ");
while($result = mysql_fetch_array($query)){

    $colors = $result['colors'];
    $id = $result[id_item];
    if(!isset($color))
    {
        $color = explode(",",$result['color']);
    }
    if(!isset($stock))
    {
    $stock = explode(",",$result['stock']);
    }

    $flag = array_search($colors,$color);
    $stock[$flag] = $stock[$flag] - $result['qty'];
}

$stock = implode(',',$stock);
mysql_query("update item set stock = '".$stock."' where id_item = ".$id);

不过老实说,您使用数据库的方式很糟糕。这不是应该使用数据库的方式。

于 2013-03-21T20:22:18.880 回答