2013-03-21 72 views
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。 任何人都可以告訴我如何做到這一點,或任何人都可以告訴我在我的代碼中有一個錯誤? THX

+3

[**請不要在新代碼中使用'mysql_ *'函數**](http://bit.ly/phpmsql)。他們不再被維護[並且被正式棄用](http://j.mp/XqV7Lp)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。 – Kermit 2013-03-21 20:13:00

+1

您可以修復數據結構的任何可能性,以便將列表存儲在表中而不是字符串?您的數據結構對關係數據庫的使用非常差,從而導致難以解決此問題。 – 2013-03-21 20:13:21

+0

是的,我認爲是這樣,如果我爲不同的顏色製作自己的領域會很容易。我只知道,我可以做到這一點,如果不能,也許我會改變表結構.. – 2013-03-21 20:19:51

回答

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); 

我會說實話,雖然,您使用的數據庫是可怕的方式。這不是應該如何使用數據庫。

+0

採取編輯版本 – 2013-03-21 20:30:55

+0

我會先嚐試它,thx;) – 2013-03-21 20:33:00

+0

它的工作,thx。首先,我知道這種結構非常糟糕,而且我知道這種結構在未來會變得複雜,但我必須這樣做是出於某種原因。我現在也許這將是最好的方式,如果我做自己的領域。無論如何,thx爲您的答案和建議..;) – 2013-03-21 20:41:24