我有这样的表项目:
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。 任何人都可以告诉我如何实现这一点,或者任何人都可以告诉我我的代码中有错误? THX
答案 0 :(得分: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);
我会说实话,你使用数据库的方式很糟糕。这不是数据库的使用方式。