2012-01-12 25 views
1

私はアイテムのリストを含むデータベーステーブルを持っています。関連するフィールドは、「アイテム名」および「list_order」です。JQuery UI Sortableを使用してデータベースフィールドを並べ替える

アイテムがソートされるたびにajax呼び出しをトリガーすることで、テーブルの「list_order」列を並べ替えることができます。例えば

、私は、次のデータがある場合

Milk  1 
Cookies 2 
Cereal 3 
Iは、リストの一番上に穀物をドラッグするjQueryのUIを使用し、これは

Milk  2 
Cookies 3 
Cereal 1 
としてデータベースに反映したいと思い

誰かが例やリンクを教えたり、これを行う方法について説明したりできますか? TIA。

答えて

2

あなたはlist_position =>のitem_idの配列でPHPスクリプトにAJAX呼び出しを行うことができ、その後、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); 
?> 
+1

単一のUPDATEは 'u pdate ... set position = case id when ... end id in(...) 'は、基本的にCASEを連想配列のSQLバージョンとして使用します。 –

+0

私は、更新されるケースの数が何百にも及ぶという問題を抱えています。その結果のクエリは、 'CASE WHEN THEN'メソッドを使用すると遅くなります。 –

+0

影響を受ける行のみSQL UPDATEを送信できますか?したがって、 'listItem_2'と' listItem_3'を入れ替えた場合、それらの2つを更新し、1と4だけを残すべきですか? (更新する必要がある場合にのみ数百の行を一度に更新するなど、サーバーリソースを最小限に抑えるため) – Jon

関連する問題