[英]Updating multiple MYSQL rows via PHP
我對PHP相當陌生,我了解基礎知識,但不確定如何在PHP中一次更新多行嗎? 形式與此類似:
<form action="sortorder.php" id="sortorder">
<input style='width:20px;' type='text' name='photo' value='1'>
<input style='width:20px;' type='text' name='sortorder' value='1'>
<input style='width:20px;' type='text' name='photo' value='2'>
<input style='width:20px;' type='text' name='sortorder' value='2'>
<input style='width:20px;' type='text' name='photo' value='3'>
<input style='width:20px;' type='text' name='sortorder' value='3'>
</form>
我需要將類似的代碼應用於以下內容
UPDATE photos SET sortorder = <input> WHERE id = '1';
UPDATE photos SET sortorder = <input> WHERE id = '2';
我只是不知道如何獲取多個動態數據並更新它們。 有人可以指出我正確的方向嗎? 我意識到我需要將它們放入一個數組,但是我只是不知道如何。
先感謝您。
假設您有ID 1,2,3,4。 您可以執行以下操作:
UPDATE photos SET sortorder = <yourvalue> WHERE id IN (1,2,3,4);
現在,無需顯式編寫IN (1,2,3,4)
您就可以動態生成要更新的值。 可以通過PHP或SQL:
UPDATE photos SET sortorder = <yourvalue>
WHERE id IN
(SELECT id from anotherTable WHERE otherattribute = someotherValue);
您應該注意,只有文本必須以'
-不能寫數字! 對於您的示例,我假設id
是一個數字而不是文本-如果確實是文本(或char / varchar),則需要編寫... IN ('1','2','3','4')
。 但我建議您使用整數作為ID。
更新:要獲取輸入的特定值,可以執行以下操作:
<input ... name='photo[]' value='1' />
<input ... name='sortorder[]' value='1' />
這樣,您在發送表單時將獲得兩個數組: $_POST[photo]
和$_POST[sortorder]
。
現在遍歷這兩個代碼(很抱歉,如果語法不正確,很長時間沒有使用PHP,但是想法應該很清楚):
for($i = 0; $i < photo.length; $i++){
// your query here
// something like:
UPDATE photos SET sortorder = sortorder[i] WHERE id = photo[i];
// of course you have to sanitize your input!
}
就像我說的那樣:我不確定這是否就是用PHP編寫的方式,但是這個想法是遍歷數組並將這些值帶入查詢中。
根據您的查詢
UPDATE photos SET sortorder = WHERE id = '1';
UPDATE photos SET sortorder = WHERE id = '2';
id列是varchar而不是int,並且您還沒有指定要按排序順序存儲的內容。
我正在考慮以下查詢的解決方案
UPDATE photos SET sortorder = '1' WHERE id = '1';
UPDATE photos SET sortorder = '2' WHERE id = '2';
在這種情況下,您應該查詢如下:
UPDATE photos SET sortorder = id;
如果sortorder為int且id為varchar,則查詢應為
UPDATE photos SET sortorder = CAST(id as unsigned);
如果您只想更新某些特定值,則應該像
UPDATE photos SET sortorder = CAST(id as unsigned) where id in ('1','2','3');
它表明您想使插入sql更有效。 但是實際上,每次按id更新一行將縮短鎖定時間並有助於提高並發能力。 另一方面,無法通過一個sql在不同條件下更新不同的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.