Saturday 29 September 2012

SImple Ajax Pagination

<?php
/*
 ********************************************************************
THIS IS PAGINATION CLASS FILE
 ********************************************************************
*/
 class Paginate {

    /**
     * Which method of pagination are we using? AJAX is the only one for right now.
     * @var string
     */
    public $method = 'ajax';

    /**
     * How many records do we want per page
     * @var integer
     */
    public $rows_per_page = 20;

    /**
     * This variable holds the number of pages we will have
     * @var integer
     */
    public $pages = 0;

    /**
     * Holds the current page number. Default is page 1.
     * @var integer
     */
    public $current_page_number = 1;

    /**
     * How many records to display in SQL.
     * @var integer
     */
    public $sql_offset = 0;

    /**
     * This will be appended to the SQL query that is run to retrieve records
     * @var string
     */
    public $sql_append = '';

    /**
     * Holds total records received from query
     * @var integer
     */
    public $query_total_records = 0;

    /**
     * Holds the output for the generated pagination links
     * @var string
     */
    public $links = '';

    /**
     * How many links to display before and after the current page
     * @var integer
     */
    public $link_spread = 4;

    /**
     * Given the total records returned by a query we can set up how many
     * pages are needed.
     * @param   int $query_total_records is the total record count of the
     *          returned query
     */
    public function set_pages($query_total_records) {
        $this->query_total_records = $query_total_records;
        $this->pages = ceil($this->query_total_records / $this->rows_per_page);
    }

    /**
     * This method will set sql_append with the correct offset to append
     * to our queries so that page navigation works.
     */
    public function set_query_offset_append() {
        if ($this->current_page_number > $this->pages)
            $this->current_page_number = $this->pages;
        if ($this->current_page_number < 1)
            $this->current_page_number = 1;
        // calculate offset bases on rows per page
        $this->sql_offset = ($this->current_page_number - 1) * $this->rows_per_page;
        // if we have more records than rows per page append offset
        if ($this->query_total_records > $this->rows_per_page)
            $this->sql_append = " LIMIT {$this->sql_offset}, {$this->rows_per_page}";
    }

    /**
     * This method will build pagination links and set the
     * pagination_links with the proper HTML
     * @param   array $params used to give extra options
     *          class = span class
     *          class_current = span class of the current page number
     *          function = name of the function that will do the AJAX magic whatever(pageNum)
     */
    public function build_pagination_links($params = array()) {
        if ($this->current_page_number > 1) {
            $this->links = '<span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(1);"' : '';
            $this->links .= '><< First</a></span> <span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $prev_page = $this->current_page_number - 1;
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $prev_page . ');"' : '';
            $this->links .= '>< Prev</a></span> ';
        }

        // loop over the rest of the links
        for ($i=($this->current_page_number-$this->link_spread);$i<(($this->current_page_number+$this->link_spread)+1);$i++) {
            if (($i > 0) && ($i <= $this->pages)) {
                if ($i == $this->current_page_number) {
                    // current page link
                    $this->links .= '<span ';
                    $this->links .= (!empty($params['class_current'])) ? 'class="'.$params['class_current'].'"' : '';
                    $this->links .= '><b>'.$i.'</b></span> ';
                } else {
                    // not current link
                    $this->links .= '<span ';
                    $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
                    $this->links .= '><a href="#" ';
                    $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $i . ');"' : '';
                    $this->links .= '>' . $i . '</a></span> ';
                }

            }
        }

        if ($this->current_page_number != $this->pages) {
            // not on last page        
            $this->links .= '<span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $next_page = $this->current_page_number + 1;
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $next_page . ');"' : '';
            $this->links .= '>Next ></a></span> ';
            $this->links .= '<span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $this->pages . ');"' : '';
            $this->links .= '>Last >></a></span> ';
        }
    }

 }

 ?>

INCLUDE PAGINATION CLASS INTO YOUR PHP CODE

<?php
include('path/to/class/paginate.php');

// query the database for our registration
$db = new Database('host', 'user', 'pass', 'dbname');
$query = "SELECT * FROM REGISTRATION";
$result = $db->query($query);

// get a count of returned  our query
$numCount = $db->num_rows($result);

$pagination = new Paginate();
$pagination->set_pages($numCount);

// now we need to check if we got a page number from POST or GET
if (isset($_POST['page']) && !empty($_POST['page']))
    $pagination->current_page_number = $_POST['page'];

// we need to take care of the offset to append to our sql queries
$pagination->set_query_offset_append();

// now we want to attach the offset to our original query
$query = $query . $pagination->sql_append;
$strQuery = mysql_fetch_asssc($query);

// start output
echo "<div id='pagination'>"

// Now we want to generate our PHP pagination links.
// Notice the last set of key value pair, function is js_paginate, which is the name of JavaScript function
// we will use. js_paginate(page)
$params = array('class'=>'pagination', 'class_current'=>'pagination-current', 'function'=>'js_paginate');
$pagination->build_pagination_links($params);
echo $pagination->links;
echo '<table>';

foreach ($$strQueryas $num => $sqlResult) {
    echo '<tr><td>' . $sqlResult->name . '</td></tr>';
}
?>





USE BELOW JAVASCRIPT FUNCTION HEAD TAG IN SAME PAGE
function js_paginate(page) {
    $('#pagination').load( // this is the id of the div holding our list
        'pagename.php', // the script that handles our listing from above
        {'page':page}
    );
}

//SOME CODE SETTING IN CLASS
$pagination = new Paginate();
// set how many rows to show per page
$pagination->rows_per_page = 10;

// set the link spread 1 2 3 4 (5) 6 7 8 9 of how many links to the left and right of the current page
$pagination->link_spread = 5;

Wednesday 5 September 2012

jQuery Ajax Sending Request

Send data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert messge will display to user.

var request=$.ajax({
                url:'ajax_filter_search.php',
                data:'action=filterSearch&filterId='+filterId+'&restId='+restId,
                });
           
            // IF REQUEST IS DONE   
            request.done(function(result){
                setTimeout( function() {
                        $('#middlecontent').html(result);
                    }, 800 );   
                });
           
            // IF REQUEST IS FAIL   
            request.fail(function(jqXHR,textStatus) {
              alert( "Request failed: " + textStatus );
            });    

Tuesday 4 September 2012

Simple Php Classes

<?php
class Database {

    private $host;
    private $user;
    private $pass;
    private $name;
    private $link;
    private $error;
    private $errno;
    private $query;

    function __construct($host, $user, $pass, $name = "", $conn = 1) {
        $this -> host = $host;
        $this -> user = $user;
        $this -> pass = $pass;
        if (!empty($name)) $this -> name = $name;      
        if ($conn == 1) $this -> connect();
    }

    function __destruct() {
        @mysql_close($this->link);
    }

    public function connect() {
        if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass)) {
            if (!empty($this -> name)) {
                if (!mysql_select_db($this -> name)) $this -> exception("Could not connect to the database!");
            }
        } else {
            $this -> exception("Could not create database connection!");
        }
    }

    public function close() {
        @mysql_close($this->link);
    }

    public function query($sql) {
        if ($this->query = @mysql_query($sql)) {
            return $this->query;
        } else {
            $this->exception("Could not query database!");
            return false;
        }
    }

    public function num_rows($qid) {
        if (empty($qid)) {         
            $this->exception("Could not get number of rows because no query id was supplied!");
            return false;
        } else {
            return mysql_numrows($qid);
        }
    }

    public function fetch_array($qid) {
        if (empty($qid)) {
            $this->exception("Could not fetch array because no query id was supplied!");
            return false;
        } else {
            $data = mysql_fetch_array($qid);
        }
        return $data;
    }

    public function fetch_array_assoc($qid) {
        if (empty($qid)) {
            $this->exception("Could not fetch array assoc because no query id was supplied!");
            return false;
        } else {
            $data = mysql_fetch_array($qid, MYSQL_ASSOC);
        }
        return $data;
    }

    public function fetch_all_array($sql, $assoc = true) {
        $data = array();
        if ($qid = $this->query($sql)) {
            if ($assoc) {
                while ($row = $this->fetch_array_assoc($qid)) {
                    $data[] = $row;
                }
            } else {
                while ($row = $this->fetch_array($qid)) {
                    $data[] = $row;
                }
            }
        } else {
            return false;
        }
        return $data;
    }

    public function last_id() {
        if ($id = mysql_insert_id()) {
            return $id;
        } else {
            return false;
        }
    }

    private function exception($message) {
        if ($this->link) {
            $this->error = mysql_error($this->link);
            $this->errno = mysql_errno($this->link);
        } else {
            $this->error = mysql_error();
            $this->errno = mysql_errno();
        }
        if (PHP_SAPI !== 'cli') {
        ?>

            <div class="alert-bad">
                <div>
                    Database Error
                </div>
                <div>
                    Message: <?php echo $message; ?>
                </div>
                <?php if (strlen($this->error) > 0): ?>
                    <div>
                        <?php echo $this->error; ?>
                    </div>
                <?php endif; ?>
                <div>
                    Script: <?php echo @$_SERVER['REQUEST_URI']; ?>
                </div>
                <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?>
                    <div>
                        <?php echo @$_SERVER['HTTP_REFERER']; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php
        } else {
            echo "+-------+ +-------+\n";
            echo "| +---+ | |       |\n";
            echo "| |   | | |  +----+\n";
            echo "| |   | | |  |     \n";
            echo "| |   | | |  +----+\n";
            echo "| |   | | |       |\n";
            echo "| +---+ | |  +----+\n";
            echo "|  ___  | |  |     \n";
            echo "| (   ) | |  +----+\n";
            echo "|  ---  | |       |\n";
            echo "+-------+ +-------+\n";
            echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n";
        };
    }

}
?>

To use this PHP MySQL class an example below:
$db = Database('localhost', 'username', 'password', 'database_name');
// query database
$q = "SELECT * FROM articles ORDER BY id DESC";
$r = $db->query($q);
// if we have a result loop over the result
if ($db->num_rows($r) > 0) {
  while ($a = $db->fetch_array_assoc($r)) {
    echo "{$a['author']} wrote {$a['title']}\n";
  }
}

// fetch array of articles with less code
$q = "SELECT * FROM articles ORDER BY id DESC";
$a = $db->fetch_all_array($q);
if (!empty($a)) {
  foreach ($a as $k => $v) {
    echo "{$v['author']} wrote {$v['title']}\n";
  }
}