Creating Sortable Lists With PHP And Ajax
Creating The Order Processing Script
Now we need to write the script that processes any ordering changes to the list. Once this is done, we’ll add the functionality to our list to actually call this script.
When a change to the list occurs, an array of the movie ID’s in their new order is generated, so our processor needs to take this array, and then update the ranking field in the database accordingly.
To achieve this, we create a new function in our movies.php, called processMoviesOrder(). Add this function after the getMovies() function in movies.php.
processMoviesOrder() for MySQL
function processMoviesOrder($key) { if (!isset($_POST[$key]) || !is_array($_POST[$key])) return; $movies = getMovies(); $queries = array(); $ranking = 1; foreach ($_POST[$key] as $movie_id) { if (!array_key_exists($movie_id, $movies)) continue; $query = sprintf('update movies set ranking = %d where movie_id = %d', $ranking, $movie_id); mysql_query($query); $ranking++; } }
processMoviesOrder() for PostgreSQL
function processMoviesOrder($key) { if (!isset($_POST[$key]) || !is_array($_POST[$key])) return; $movies = getMovies(); $queries = array(); $ranking = 1; foreach ($_POST[$key] as $movie_id) { if (!array_key_exists($movie_id, $movies)) continue; $query = sprintf('update movies set ranking = %d where movie_id = %d', $ranking, $movie_id); pg_query($query); $ranking++; } }
processor.php for MySQL and PostgreSQL
Now here is the script that calls the processMoviesOrder script. Note that we pass the form index that holds the ordering values. There’s no great reason for doing this other than if you change the form key then you only have to change it here (note that this is the unordered list ID from index.php).
require_once('database.php'); require_once('movies.php'); if (!dbConnect()) exit; processMoviesOrder('movies_list');

![Prototype and Scriptaculous in Action [Ajax]](http://ecx.images-amazon.com/images/I/51i%2BlUTDmbL._SL75_.jpg)