Google like Pagination

In the beginning of my career, every technical interview has this question; "How do you write pagination script in PHP?". I think you too faced the same issue. It was very important to answer this because every application is developed to list set of information and off-course you can't show every thing in a single page. It will irritate the user to scroll to the bottom of page to read.

So, the pagination. Divide the list of items in number of pages and navigate to each by clicking on each page number displayed. At the beginning, the pagination was simple was limited to 10-15 pages, but after some time in real time the requirement has grown to 10 multiple pages. Solution was to show first few page numbers, last few page numbers and in middle show the ellipsis(...). As you navigate to any page it would show definite page numbers to both the sides.


/**
 * Pagination file
 * 
 * This file provides the google like pagination solution
 * 
 * @category Saral
 * @package Pager
 * @version  0.1
 * @since  0.1
 */

/**
 * Pager class
 *
 * Class is used generate google like pagination links
 *
 * @category Saral
 * @package Pager
 * @version Release: 0.1
 * @since 26.Nov.2013
 * @author Sailesh Jaiswal
 */
class Pager
{

    /**
     *
     * css class name for links container
     *
     * @var string
     */
    private $class_pagination = 'pagination';

    /**
     *
     * css class name for default style for links
     *
     * @var string
     */
    private $class_default = 'page';

    /**
     *
     * css class name for disabled style for links
     *
     * @var string
     */
    private $class_disabled = 'disabled';

    /**
     *
     * css class name for current/selected link style
     *
     * @var string
     */
    private $class_current = 'current';

    /**
     *
     * used to set the css classes for links
     *
     * @param string $pagination            
     * @param string $default            
     * @param string $disabled            
     * @param string $current            
     */
    function setStyles($pagination = '', $default = '', $disabled = '', $current = '')
    {
        if ($pagination != '') {
            $this->class_pagination = $pagination;
        }
        if ($default != '') {
            $this->class_default = $default;
        }
        if ($disabled != '') {
            $this->class_disabled = $disabled;
        }
        if ($current != '') {
            $this->class_current = $current;
        }
    }

    /**
     *
     * generates pagination links
     *
     * @param string $url   url of the page         
     * @param integer $current_page   current page         
     * @param integer $total_records   total records         
     * @param integer $rpp            records per page
     * @param integer $adjacents      how many pages to show both the side of the current page in case if there are plenty of pages      
     * @return string
     */
    function showLinks($url, $current_page, $total_records, $rpp = 5, $adjacents = 2)
    {
        $class_pagination = $this->class_pagination;
        $page = $this->class_default;
        $current = $this->class_current;
        $disabled = $this->class_disabled;
        
        $pagination = "";
        $prev = $current_page - 1; // previous page is page - 1
        $next = $current_page + 1; // next page is page + 1
        $lastpage = ceil($total_records / $rpp); // lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1; // last page minus 1
        $prev = $url . '?page=' . $prev;
        if ($lastpage > 1) {
            $pagination .= "<div><ul class=\"$class_pagination\">";
            // previous button
            if ($current_page > 1)
                $pagination .= "<li><a href=\"$prev\" class=\"$page\"> << previous</a></li>";
            else
                $pagination .= "<li><span class=\"$disabled\"> << previous</span></li>";
            
            // pages
            if ($lastpage < 7 + ($adjacents * 2)) // not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter ++) {
                    $i = $url . '?page=' . $counter;
                    if ($counter == $current_page)
                        $pagination .= "<li class=\"$current\"><a>$counter</a></li>";
                    else
                        $pagination .= "<li><a href=\"$i\" class=\"$page\">$counter</a></li>";
                }
            } elseif ($lastpage > 5 + ($adjacents * 2)) // enough pages to hide some
            {
                // close to beginning; only hide later pages
                if ($current_page < 1 + ($adjacents * 2)) {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter ++) {
                        $i = $url . '?page=' . $counter;
                        if ($counter == $current_page)
                            $pagination .= "<li class=\"$current\"><a>$counter</a></li>";
                        else
                            $pagination .= "<li><a href=\"$i\" class=\"$page\">$counter</a></li>";
                    }
                    $lpm11 = $url . '?page=' . $lpm1;
                    $lastpage1 = $url . '?page=' . $lastpage;
                    $pagination .= "<li><a href='javascript: void(0)'>...</a></li>";
                    $pagination .= "<li><a href=\"$lpm11\" class=\"$page\">$lpm1</a></li>";
                    $pagination .= "<li><a href=\"$lastpage\" class=\"$page\">$lastpage</a></li>";
                } // in middle; hide some front and some back
                elseif ($lastpage - ($adjacents * 2) > $current_page && $current_page > ($adjacents * 2)) {
                    $pagination .= "<li><a href=\"$url?page=1\" class=\"$page\">1</a></li>";
                    $pagination .= "<li><a href=\"$url?page=2\" class=\"$page\">2</a></li>";
                    $pagination .= "<li><a href='javascript: void(0)'>...</a></li>";
                    for ($counter = $current_page - $adjacents; $counter <= $current_page + $adjacents; $counter ++) {
                        $i = $url . '?page=' . $counter;
                        if ($counter == $current_page)
                            $pagination .= "<li class=\"$current\"><a>$counter</a></li>";
                        else
                            $pagination .= "<li><a href=\"$i\" class=\"$page\">$counter</a></li>";
                    }
                    $lpm11 = $url . '?page=' . $lpm1;
                    $lastpage1 = $url . '?page=' . $lastpage;
                    $pagination .= "<li><a href='javascript: void(0)'>...</a></li>";
                    $pagination .= "<li><a href=\"$lpm11\" class=\"$page\">$lpm1</a></li>";
                    $pagination .= "<li><a href=\"$lastpage1\" class=\"$page\">$lastpage</a></li>";
                } // close to end; only hide early pages
                else {
                    $pagination .= "<li><a href=\"$url?page=1\" class=\"$page\">1</a></li>";
                    $pagination .= "<li><a href=\"$url?page=2\" class=\"$page\">2</a></li>";
                    $pagination .= "<li><a href='javascript: void(0)'>...</a></li>";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter ++) {
                        $i = $url . '?page=' . $counter;
                        if ($counter == $current_page)
                            $pagination .= "<li class=\"$current\"><a>$counter</a></li>";
                        else
                            $pagination .= "<li><a href=\"$i\" class=\"$page\">$counter</a></li>";
                    }
                }
            }
        
            // next button
            if ($current_page < $counter - 1) {
                $next = $url . '?page=' . $next;
                $pagination .= "<li><a href=\"$next\" class=\"$page\">next >></a></li>";
            } else {
                $pagination .= "<li><span class=\"$disabled\">next >></span></li>";
            }
            $pagination .= "</ul></div>\n";
        }
        return $pagination;
    }
}

$total_records = 100; //total records that you want to show as paginated
$page = $_GET['page'];
$pager = new Pager;
echo $pager->showLinks("http://example.com/posts.php", $page, $total_records, 10, 2);

Validation and Submission of form using jQuery :: Easiest Solution

In any application, form validation and submission to server is so common and redundant; there are multiple ways of doing it. And the best and easiest way that I do use or recommend is jQuery solution. 

Most popular jQuery plugins are the best solution, they have the best solution ever. 

One, jQuery Validator written and maintained by Jorn Zaefferer, a member of the jQuery team, lead developer on the jQuery UI team and maintainer of QUnit.

Two, jQuery Form by malsup, it has various plugins and solutions. Another plugin that I like from same developer is jQuery BlockUI. (give a try).


 
 
 
 
 
Name:
Email:
Note: To avoid unexpected behavior, maintain same form and fields names and id selector values. Need further explanation, let me know.

Email already exists using jQuery

It is the common requirement for any web application either it is PHP, .net, JSP etc., which has users involved. When creating/adding user from admin or end user registration we should check whether username or email address already exists. It will help to have unique registrations to our application and avoid confusion between various users. 

I see many developers struggle with this by submitting the form to server side script and validate their from database, in case username/email address already exists they take the pain to go back to previous page or form and show the error message with other form data filled. 

Few use AJAX to send the information onblur or onkeyup or onkeydown but face difficulties to stop form submission. Here is the simple solution that would help in validating username or email address existence without much hassle. 

Solution comes from popular jQuery Validator plugin I'm using this from ages. 

HTML Code:
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
        <script>
              $(function(){
                    $('#UserForm').validate({
                           rules:{
                                   Name: {required: true},
                                   EmailID: { required: true, email: true, 
                                     remote: {
                                        url: "http://localhost/user/check-email",
                                        type: "post",
                                        data: {
                                              EmailID: function() {
                                                  return $( "#EmailID" ).val();
                                              },
                                              UserID: $('#UserID').val()
                                        }
                                     }
                                 }
                           }   
                    });
              });
        </script>
    </head>
    <body>
        <form action="" id="UserForm" method="post" name="UserForm">
            Name: <input id="Name" name="Name" type="text" />
            Email ID: <input id="EmailID" name="EmailID" type="text" />
            <input id="UserID" name="UserID" type="hidden" value="0" />
            <input id="Submit" name="Submit" type="submit" value="Submit" />
        </form>
</body>
</html>

 The remote block will do the trick, it sends the current field value to server side URL "http://localhost/user/check-email". This URL can be any file URL where it sends EmailID value using POST method and there you've to write SQL query to search in DB and if exists print 'false' otherwise 'true'. (Note: don't write return true or return false, just print true or false in quotes)

We can pass UserID as zero for new insertion for update UserID can be unsigned integer so that you can check if EmailID is same for other than selected UserID.

Sorting second dimension array

We can sort the second dimension array like table, for example


$users = array(
	array('name' => 'Mr. B', 'age' => 34), 
	array('name' => 'Mr. A', 'age' => 33),
	array('name' => 'Mr. C', 'age' => 32)
);

If you want to sort the array based on the name or age, here is the solution:



function arraySortByColumn(&$arr, $col, $dir = SORT_ASC){
	$sort_col = array();
	foreach ($arr as $key => $row) {
		$sort_col[$key] = $row[$col];
	}
	array_multisort($sort_col, $dir, $arr);
}

arraySortByColumn($users, 'name', SORT_DESC);
print_r($users);