你應該能夠使一個AJAX調用PHP腳本與list_position => ITEM_ID的數組,然後在PHP中遍歷所述陣列和
update table set list_position='$key' where id='$val';
,然後你當然會被list_position排序在選擇有關未來查詢的數據時。
編輯:剛剛發現這個例子在線@http://wil-linssen.com/entry/extending-the-jquery-sortable-with-ajax-mysql/
JS:
<script type="text/javascript">
// When the document is ready set up our sortable with it's inherant function(s)
$(document).ready(function() {
$("#test-list").sortable({
handle : '.handle',
update : function() {
var order = $('#test-list').sortable('serialize');
$("#info").load("process-sortable.php?"+order);
}
});
});
</script>
HTML:
<pre>
<div id="info">Waiting for update</div>
</pre>
<ul id="test-list">
<li id="listItem_1">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 1 </strong>with a link to <a href="http://www.google.co.uk/" rel="nofollow">Google</a>
</li>
<li id="listItem_2">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 2</strong>
</li>
<li id="listItem_3">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 3</strong>
</li>
<li id="listItem_4">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 4</strong>
</li>
</ul>
<form action="process-sortable.php" method="post" name="sortables">
<input type="hidden" name="test-log" id="test-log" />
</form>
PHP:
<?php
/* This is where you would inject your sql into the database
but we're just going to format it and send it back
*/
foreach ($_GET['listItem'] as $position => $item) :
$sql[] = "UPDATE `table` SET `position` = $position WHERE `id` = $item";
endforeach;
print_r ($sql);
?>
你可以做的更新中單一的更新像'u pdate ... set position = case id when ... end where(in)(...)',基本上使用CASE作爲關聯數組的SQL版本。 – 2012-01-12 23:35:32
我遇到了一個問題,即正在更新的案例數量達到幾百個,使用'CASE WHEN THEN'方法生成的查詢速度很慢。 – 2013-08-28 08:59:39
是否可以僅爲受影響的行發送SQL UPDATE?所以如果'listItem_2'和'listItem_3'被交換,它應該只更新這兩個並且保留1和4? (爲了最小化服務器資源,例如當只需要更新時需要一次更新數百行) – Jon 2017-02-23 21:43:06