2012-12-23 22 views
2

請我有三列的表:PHP的MySQL更新在表中標識的位置和家長

id (this is the id of my table) 
parent (this is the parent) 
position (and this is the position) 

而且我有這個數組$_arr['menu']

array (size=3) 
    13 => 
    array (size=1) 
     'parent' => string '0' (length=1) 
    14 => 
    array (size=1) 
     'parent' => string '13' (length=2) 
    25 => 
    array (size=1) 
     'parent' => string '0' (length=1) 

我想更新可能表中有這些值的數組$ _arr ['menu']

我想象做這樣的事情,但在一個查詢(可能使用情況):

UPDATE table SET position = 1, parent = 0 WHERE id = 13; 

UPDATE table SET position = 2, parent = 13 WHERE id = 14; 

UPDATE table SET position = 3, parent = 0 WHERE id = 25; 

請高手,如何從陣列,以及如何做好更新獲取這些值!

非常感謝

+0

你想在一個更新中做兩個更新? –

+0

是的,實際上陣列可能有兩個以上! –

+0

並請如何從數組中獲得這些值! –

回答

3

我不知道我得到了你的問題,但我會寫我的片段。 (我不記得php的語法,它沒有測試,但我認爲它顯示了我想說的)

try { 
    $db->beginTransaction(); 
    $increment = 0; 
    foreach ($arr as $id => $innerArray) { 
      $db->query("UPDATE table SET position = ".(++$increment).", parent = ".$innerArray['parent']." WHERE id =".$id); 
    } 
    $db->commit(); 
} catch (Exception $e) { 
    $db->rollback(); 
} 
+1

使用交易+1,但您怎麼知道他在使用PDO?其次,使用'$ db-> prepare(「query」)'並將這些值作爲參數綁定可以防止SQL注入。 – dbf

+2

我只想顯示這個想法。當然,代碼必須糾正,參數應該設置,而不是連接 – mariami

+0

我明白了你的想法,你真是太棒了! –