2013-03-25 16 views
3

更新與數組元素的整個列我有一個表用戶X這樣的:在MySQL

id----------text---------num   
1-----------foo-----------0 
2-----------bar-----------0 
3-----------widget--------0 
4-----------widget--------0 
5-----------widget--------0 
6-----------widget--------0 
7-----------widget--------0 
8-----------widget--------0 

我有一個這樣的數組:

$numeros = array(30, 50, 60, 70, 90, 110, 130, 150); 

所以我想打一個查詢,得到從$ numeros和更新到我的專欄每個結果「編號」(從ID = 1開始)是這樣的:

id----------text--------------num   
1-----------foo--------------30 
2-----------bar--------------50 
3-----------widget-----------60 
4-----------widget-----------70 
5-----------widget-----------90 
6-----------widget-----------110 
7-----------widget-----------130 
8-----------widget-----------150 

可以進行更新單個更新(或循環內的多個)查詢?怎麼樣?

+1

但是,您可以在循環中使用預準備語句,並在每次迭代中循環遍歷數組綁定不同的值。 – 2013-03-25 19:52:29

+0

這是關係數據庫的一個大問題,難以提出垂直請求。如果你想這樣做,使用MongoDB和JavaScript! – StenW 2013-03-25 19:55:16

+0

如果你有一個像id一樣的迭代列,它並不是那麼糟糕。但是,是的,如果一個數字跳過id,然後他擰了 – 2013-03-25 19:57:43

回答

0

你可以嘗試這樣的事:

$query = "UPDATE userx SET num=? WHERE id=?"; 
for($j = 0, $j < sizeof(numeros); $j++) 
{ 
    $index = $j+1;   
    $stmt = $db->prepare($query); 
    $stmt->bind_param('ii', $numeros[$j], $index); 
    $stmt->execute(); 
} 

所以雖然它不是技術上一個查詢,你只寫一次

+0

我要去看看傑夫。謝謝 – JuanFernandoz 2013-03-25 20:09:55

+0

我不確定$ j + 1是否可以在bind_param調用中工作,但我的觀點是數組從0開始,而id號從1開始,所以你必須把$ j + 1放在那裏以某種方式得到正確的關聯 – 2013-03-25 20:11:25

+0

是的,這不起作用,但我試圖解決這個使用for循環是我想的唯一方法。 – JuanFernandoz 2013-03-25 20:24:19

0

你可以嘗試像每一個元素用一個函數調用更新通過for循環的另一個函數。 IE

#CODE TO CONNECT TO Mysql database 
#then call function to update these column elements 
updateColumns(); 
function updateColumns(){ 
    $query = "SELECT column FROM table"; 
    $result = mysql_query($query); 

    if(!$result){ 
     echo "Error message you want.</br>"; 
     echo mysql_error(); 
    } 
    else{ 
     $count = mysql_num_rows($result); 
     if($count){ 
      # There are rows. now check if there is a match 
      while($row=mysql_fetch_array($result)){ 
       #cycle through each row of the $result column 
       foreach($row as $key => $value){ 
        if($key){ 
         updateThisColumnsValue($value); 
        } 
       } 
      } 
     } 
    } 
} 
function updateThisColumnsValue($value){ 
    $query = "UPDATE table SET columnToCHange='newValue' WHERE referenceColumnName = '$value'"; 
    $result = mysql_query($query); 
    if(!result){ 
     error message 
    }# that should be it. 
} 

而且,這裏是一個鏈接的SQL更新功能w3school.sql 我希望這有助於。