2013-11-21 23 views
0

我也發現了類似的問題,包括一個計算器上的位置:Update echoed data using WHILE loop. Only updates one record從while語句更新mysql行的正確foreach表達式是什麼?

我一直在使用這些例子我使用有問題,並正在尋找一個特定的foreach表達式中使用。我相信這個解決方案非常簡單。

表「測試」:

+--------+ 
|id|text | 
+--+-----+ 
|0 |Text1| 
+-+------+ 
|1 |Text2| 
+-+------+ 
|2 |Text3| 
+-+------+ 
|4 |Text4| 
+-+------+ 
|5 |Text5| 
+-+------+ 
|6 |Text6| 
+-+------+ 
|7 |Text7| 
+-+------+ 

甲PDO製備語句與選擇查詢選擇所有表中的行「測試」執行。該行是while語句獲取每一行被放置到輸入用戶改變「文本」字段中的數據像這樣:由

$sth = $db->prepare("SELECT * FROM test ORDER BY id"); 
$sth->execute(); 

echo '<form class="ajax" method="post">'; 

while($row = $sth->fetch()) { 
echo '<input type="text" name="id" class="id" value="'.$row['id'].'" /> 
<input type="text" name="text" class="text" value="'.$row['text'].'" />'; 
} 

echo '<input type="submit" name="submit" value="submit"></form>'; 

在提交數據庫(應該)更新所有文本字段ID。

if (isset($_POST['submit'])) { 
    $text = $_POST['text']; 
    $id = $_POST['id']; 
    $sql = "UPDATE test SET text = :text WHERE id = :id"; 
    $sth = $db->prepare($sql); 
    $sth->execute(array(':text'=>($text),':id' => ($id))); 
} 

當前只有最後一行在數據庫中更新,我相信我需要將我準備好的更新語句放在foreach循環中。

事情是這樣的:

foreach($something as $something => $somethingElse) { 
    $text = $_POST['text']; 
    $id = $_POST['id']; 
    $sql = "UPDATE test SET text = :text WHERE id = :id"; 
    $sth = $db->prepare($sql); 
    $sth->execute(array(':text'=>($text),':id' => ($id))); 
} 

什麼是這裏使用正確的表達?或者,我以某種方式咆哮錯誤的樹?

感謝

山姆

回答

2

試着改變你的投入到這一點。

while($row = $sth->fetch()) { 
echo '<input type="text" name="id[]" class="id" value="'.$row['id'].'" /> 
<input type="text" name="text[]" class="text" value="'.$row['text'].'" />'; 
} 

然後你的循環

for($i=0; $i<count($_POST['id']); $i++) { 
    $id = $_POST['id'][$i]; 
    $text = $_POST['text'][$i]; 
    $sql = "UPDATE test SET text = :text WHERE id = :id"; 
    $sth = $db->prepare($sql); 
    $sth->execute(array(':text'=>($text),':id' => ($id))); 
} 
相關問題