PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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

Listing 12 movies.php
<?php
    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

Listing 13 listing-13.php
<?php
    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).

Listing 14 listing-14.php
<?php
    require_once('database.php');
    require_once('movies.php');
 
    if (!dbConnect())
        exit;
 
    processMoviesOrder('movies_list');
?>

In This Article