Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

2 May 2016

Handling Multiple Item Selection in A Listview - Android Tutorial

In this tutorial, we will learn how to respond when a user selects multiple list items in an Activity . For the purpose of this tutorial, I will be selecting multiple list items for deleting them from the database. This tutorial also covers on how to change listItem background color when the user selects multiple items.

Idea :

Listen to long press on a list item and store list id in an ArrayList if checked state is True, otherwise, if checked state is false then remove the item id from ArrayList.

pre-setup :

    Added a ListView to the layout file and attached a cursorAdepter with it.This how my final
listview looks like. 

If you are displaying list using values from the database, then make sure that the primary key name is "_id" in your database table.
Now follow below-given steps to listen for multiple list item selection
1. Set Global Variable
Context context;
private  ListView list;
private ArrayList list_item = new ArrayList<>(); // for holding list item ids
2. Change list CHOICE_MODE as follows
//(list) is my ListView           
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); // Important

3. Set MultiChoiceModeListener to your ListView variable
list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                //capture total checked items
                checkedCount = list.getCheckedItemCount();

                //setting CAB title
                mode.setTitle(checkedCount + " Selected");

                //list_item.add(id);
                if(checked){
                    list_item.add(id);     // Add to list when checked ==  true
                }else {
                    list_item.remove(id);
                }

            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                //Inflate the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.contextual_menu, menu);
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                final int deleteSize = list_item.size();
                      int itemId = item.getItemId();
                if(itemId == R.id.item_delete) {

                     for(long ids : list_item){
                            // Make proper check, if needed, before deletion 
                            String whereDelId = DBOpenHelper.COL_ID + "=" + ids;
                            int res = getContentResolver().delete(TripProvider.CONTENT_URI_START, whereDelId, null);
                            if(res == -1){
                               Log.d(TAG, "onActionItemClicked: Delete Failed for ID = "+ids);
                            }  
                     }

                }  
             Toast.makeText(context,deleteSize+" Items deleted",Toast.LENGTH_SHORT).show();

                checkedCount = 0;
                list_item.clear();
                mode.finish();
                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                // refresh list after deletion
                displayDataList();
            }
        });

Changing background Color of Selected ListView List items.

4.   Create a drawable XML for list item background.{mine is, select_list_bg,xml}
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:exitFadeDuration="@android:integer/config_shortAnimTime">
     <item  android:state_pressed="true"
         android:state_activated="true"
         android:drawable="@color/lightPink"></item>
    <item
        android:state_activated="true"
        android:drawable="@color/lightPink"></item>

    <item  android:drawable="@color/lightGreen"></item>
    <item android:state_enabled="true"
        android:drawable="@color/lightGreen"></item>
</selector>
5. Set above drawable as background to listItem
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/select_list_bg,xml"
    android:elevation="4dp">

 <!-- Your List item child views -->
</RelativeLayout>
This is the final look of the List when user selects multiple items.



27 Sept 2015

Developing Notifications In android

Notification in android  is a special type of message which is used to show useful information when your app's UI is not visible to user.
Creating Notification is very simple, even you can create Notification by simply reading android Developer Guide.
Today I am will provide a ready to use code for creating notification for your app, Just copy this code and paste in your app code.
notification
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 public void createNotification(){

     NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

// Following Three notification contents are *required 
     builder.setSmallIcon(R.drawable.notification_icon);
     builder.setContentTitle("Notification Title");
     builder.setContentText("Notification Details");

 // intent to start activity, provide Activity name where you want user to
  //to land when he/she clicks on notification, like: MainActivity

     Intent resultIntent = new Intent(this,MainActivity.class);

// Task builder to implement normal navigation 
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
     stackBuilder.addParentStack(MainActivity.class);

     stackBuilder.addNextIntent(resultIntent);

     PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
     builder.setContentIntent(resultPendingIntent);

     NotificationManager mNotifym = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// specify notification id,as first argument, i.e. I have used id=10
     mNotifym.notify(10, builder.build());


 }

 For Removing Notification use following code.
NotificationManager mNotifym = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifym.cancelAll();

This is a basic version of notification, you can add more feature by going through documentation. 

15 Aug 2015

how to Learn Android App Development ?

For Learning Android Development, there are thousands of tutorial available online, But choosing one which explains concepts in a easy way is very difficult.

Today I am going to list out some of best online resources to learn Android Development,most of these Tutorial are available free of cost. And if you are new to android Development, then before going to any other Tutorial, I would suggest you to go through following Tutorials which very useful and conceptual tutorials.

  1. Android Development for Beginners - Udacity : Video Tutorial for Complete beginners.
  2. Training for Android developers - Web based Text Tutorial Covering Basic Concepts By Google.
If during going through above Tutorial you find some topics difficult to understand then Google for that particular topic.
After going through above Tutorials you can go for any other tutorial, like Android Essential Training from Lynda.com.
Best Way to learn is to Develop small Apps,which cover basic android concepts, while learning Android Development.

So in the upcoming posts in this series of Android Development i will be posting Ideas and Concepts for Developing simple android Apps. 

2 May 2014

CurioWhite - Free and Clean Blogger template

Curiowhite is a free and clean template for blogger with many built in features like, related posts widget, Prettyprint, YouTube video embedder, auto content selector etc.
This theme is best for those bloggers who are looking for a simple and clean theme for their blog.

How to use Curiowhite blogger template ?

1. Download the template or just copy the code.
2. Go to your blogger dashboard and choose 'Template' option and then click on 'Edit HTML' tab

3. Back up your current theme
4. Now remove your older template code and paste CurioWhite template code.
5. Click on 'Save Template'.

Customizing Curiowhite blogger template configuration

1. Primary Menu


    For adding custom primary menu in header section of blog, Search for "primary menu" in the above theme code and change menu as according to your need,

2. Pretty print for posting code inside blog post
    If you want to put some code inside blog post then put your parsed code inside <pre></pre> and theme will automatically assign prettyprint class to it.For printing line number add class="linenums" to <pre> element.
Example,

       i. Without line number ,
           <pre>
                &lt;div&gt;  This is a html Div  &lt;/div&gt;
           </pre>
          final look,
    <div>This is a html Div </div>
      ii.  With line number ,
         <pre class="linenums">
              &lt;div&gt; html Div1  &lt;/div&gt;
              &lt;div&gt; html Div2 &lt;/div&gt;
         </pre>
<div>html Div1 </div>
<div>html Div2 </div>

3. Element content selector

    This theme automatically adds a function to select inner contents of <pre></pre> elements, to apply to other elements just add a onclick function 'selectElementContents(this)'.
<div ondblclick="selectElementContents(this)" > double click to select content of this div </div>

4. Related Posts widget

    This widget display posts with similar label.For more details visit this link.It takes first image of your post as a thumbnail image for display in related post. To remove it, search for 'Related posts'  and delete JavaScript and css.

5. YouTube video embedder

    This widget embeds YouTube video with the facility to load asynchronously.for details visit this link

27 Apr 2014

How to Automatically Select Content of a HTML element for copy to clipboard

Sometimes you want to let your users to select certain portion of your web content for copying to clipboard, And for this user has to select content manually.
But using below mentioned script anyone can select entire content of a HTML element just by single/double click.

Steps for implementation.
First assign a 'onclick' or 'ondblclick' function with function call (as shown below)to your HTML element.For example,
      <!-- Calling select funtion on double click -->
    <div ondblclick="selectElementContents(this)"> Double click to Select content of this div !! </div>
Now define a JavaScript function named as 'selectElementContents()',
     function selectElementContents(el) {
                    if (window.getSelection && document.createRange) {
                       // IE 9 and non-IE
                       var range = document.createRange();
                       range.selectNodeContents(el);
                       var sel = window.getSelection();
                       sel.removeAllRanges();
                       sel.addRange(range);
                    } else if (document.body.createTextRange) {
                       // IE < 9
                       var textRange = document.body.createTextRange();
                       textRange.moveToElementText(el);
                       textRange.select();
                    }
            }

That's it, Now your user can select entire content just by double clicking inside the element.
Test this code by double clicking above code area.

18 Apr 2014

Simple Jquery Masonry like script to arrange elements in vertical space

This is a Jquery script which places elements in optimal position based on available vertical and horizontal space.It arranges items in vertical column and width of vertical column is taken as width of first 'item' element.

If you have elements with 'float:left' property and if they are of different heights then arrangement looks like as following image.
But if you use this script then result looks like as follows. [ Elements are arranged in optimal position in vertical space.]

How to arrange elements in vertical space?

First create an parent element and assign a class="container" and assign class="item" to the child elements which will be arranged in vertical space.
<!-- HTML -->
<div class="container">
    <div class="item">1.</div>
    <div class="item wv">2.</div>
    <div class="item w">3.</div>
    <div class="item wv">4.</div>
    <div class="item wv">5.</div>
    <div class="item">6.</div>
    <div class="item w">7.</div>
</div>
Now provide some CSS for above elements.
/* --- CSS --- */
.item {
    display:block;
    width:80px; 
    margin:5px;
    background:grey;
    min-height:30px;
    float:left;
    position:relative;
    border:1px solid green;
}
/* classes for variation in height*/
.w {
    min-height:40px; 
}
.wv {
    min-height:50px;
}
And here comes over final Jquery Script.Note: this script arranges items in vertical column and width of vertical column is taken as width of first 'item' element, change accordingly if you want.
<!-- JavaScript -->
$(function () {


    $('.item').css('position', 'absolute');
    rearrange();
    $(window).resize(function () {
        rearrange();
    });



    function rearrange() {


        var ti = $('.item').length; //total number of items
        var cw = $('.item').first().outerWidth(true); //column width
        var mr = parseInt($('.item').first().css("marginLeft"), 10); //margin left
        var mt = parseInt($('.item').first().css("marginTop"), 10); //margin top
        var contw = $('.container').width(); //container width

        if (contw < cw) {
            return; // if column width is greater then available space.
        }

        var pl = Math.floor(contw / cw); // no. of items per line

        for (i = 1; i <= ti; i++) {
            var upElement = (i - pl);
            var left = (i % pl);
            var leftv = 0;
            if (left == 0) {
                leftv = ((pl - 1) * cw) + mr;
            } else {
                leftv = ((left - 1) * cw) + mr;
            }

            if (upElement > 0) {
                var upELem = $('.item:nth-child(' + upElement + ')');
                var upTop = upELem.position().top;
                var upH = upELem.outerHeight(true);

                $('.item:nth-child(' + i + ')').css({
                    top: (upTop + upH),
                    left: leftv
                });

            } else {
                $('.item:nth-child(' + i + ')').css({
                    top: mt,
                    left: leftv
                });
            }
        }

    }
})();

To view live demo, click here. (Change window size to view horizontal arrangement.)
This script is inspired by already available jquery plugin, Jquery Masonry.

11 Apr 2014

Script to embed YouTube videos with reduced page load

Whenever we embed YouTube video with standard IFRAME tag, our page load increases by around 400 kB for each embedded video thus increasing page load time significantly.
Today I will show you a different approach to embed YouTube videos to reduce page load time.In this approach initially we will load a thumbnail and will load video only when user clicks on this thumbnail.
For this purpose I will introduce you with a short Jquery code which will make embedding YouTube video very easy.
I hope that you have already included latest version of Jquery in your website.If not then please add it.

1. Add this css to your website's <head></head> section.
 <link rel="stylesheet" href="https://sites.google.com/site/curiohub/youtube/youtube.css" type="text/css" />
2. Add This JavaScript just before </body> tag.
<script src="https://sites.google.com/site/curiohub/youtube/youtube.js" ></script>
Now to embed YouTube video create a <div> and provide class and vid [YouTube video id.] attributes. as follows,
<!-- if YouTube url is: https://www.youtube.com/watch?v=iG9CE55wbtY then vid="iG9CE55wbtY" -->

<div class="yvid" vid="iG9CE55wbtY"></div>  <!--Default video size 640x360-->

<!-- For defining custom dimensions for video, add dimensions to the div.-->

<div class="yvid" vid="bsF_AaPXK-s" style="width:400px;height: 200px;"></div>

it's done!
Comparison for page size and load time.
video embedded without above script.

video embedded with above script

See time and page load reduced by more then 50% !!!
For live demo and source code. Visit this link
Demo video and Tutorial for Blogger.

5 Apr 2014

Creating JavaScript CountDown Timer

CountDown Timers can be useful for many online things like displaying deadline for 'a limited deals' or 'a form submission date'.
In this tutorial we will learn how to develop and implement a simple Pure JavaScript CountDown Timer. Our Final emphasis will be only on JavaScript because display styles can be changed using any custom CSS.
If you are using my css then final result will look something like following image,


So lets get started,

- First of all create a element where you want to display final result.Give each element ID as per required result, for example, 'days','hours','minutes','seconds'
<div class="countDown">
           <span id="days">00</span>     <!-- Remaining Days,id="days"-->
           <span id="hours">00</span>    <!-- Remaining hours ,id="hours"-->
           <span id="minutes">00</span>  <!-- Remaining minutes,id="minutes"-->
           <span id="seconds">00</span>  <!-- Remaining secounds,id="secounds"-->
</div>

- Include .js file,which we will create, having code for countdown,Example, my file is countdown.js, which is in same directory.
<script src="countdown.js"></script> 
- Now call countdown function with end time and callback function name as parameters.[remember, input date format, 'mm/dd/yyyy hh:mm:ss AM/PM']
<script>
           
  countdown('04/05/2014  00:45:00 PM',callback); // Date format ('MM/DD/YYYY  HH:MM:SS TT');
            
  function callback(){
       alert('Time Out'); //Callback Function Definition

  };
</script>
now we will create our countdown function,following below mentioned key concepts,
i. get current time
ii. subtract from End time [input value]
iii. convert remaining time [milliseconds] in days,hours,minutes,seconds [or add years,months, if you want]
iv. repeat step (iii) every second till remaining time is greater then or equals to zero.

//JavaScript Function for CountDown Timer, In countdown.js file 

function countdown(endT,callback) {
        var days,hours,minutes,sec,timer;
        
        end = new Date(endT);
        
        end = end.getTime(); //Get initial Date in Milliseconds,
        if (isNaN(end)) {
           alert('@ countdown.js @  "Invalid Date", valid format- mm/dd/yyyy hh:mm:ss TT ');
           return;
        }
        
        timer = setInterval(calculate,1000);//Timer to calculate remaining time

        function calculate(){
         var current = new Date();
         var remaining = parseInt((end - current.getTime())/1000);//remaining seconds, 
          
            if (remaining <= 0){
                clearInterval(timer);
                days=0;
                hours=0;
                minutes=0;
                sec=0;
                display(days,hours,minutes,sec);
                if (typeof callback === 'function' ) {
                    callback();
                }
                
            }else{
                
                days = parseInt(remaining/86400);
                remaining = (remaining%86400);
                hours = parseInt(remaining/3600);
                remaining = (remaining%3600);
                minutes = parseInt(remaining/60);
                remaining = (remaining%60);
                sec = parseInt(remaining);
                display(days,hours,minutes,sec);
                
                
            }
        }

        //Function For displaying Results in HTML page with specific ID's 
        function display(days,hours,minutes,sec) {
            var dl = days.toString().length;
            if (dl == "1") {
                sl = 2;
            }else{
                if (isNaN(dl)) {
                    sl = 3;
                }
                sl = dl;
            }
            document.getElementById("days").innerHTML = ("00"+days).slice(-sl);
            document.getElementById("hours").innerHTML = ("0"+hours).slice(-2);
            document.getElementById("minutes").innerHTML = ("0"+minutes).slice(-2);
            document.getElementById("seconds").innerHTML = ("0"+sec).slice(-2);
        }
     
    }
Finally our CountDown timer is ready and result will look something like following texts,
00 01 04 41
Add some css to make it look pretty, Below is css code to decorate above result text, use this or create your own.
/* CSS for CountDown Timer,Notice I have added labels (days,hours,minutes,seconds) using :After pseudo class, you can add these in HTML itself*/ 
            .countDown{
                display: inline-block;
                margin: auto;
            }
           
            .countDown span{
                display: block;
                background: #000;
                color: #fff;
                height: 54px;
                float: left;
                margin-right: 5px;
                padding: 8px;
                border-radius: 5px;
                font-size: 45px;
                line-height:normal;
                text-align: center;
                box-shadow: 2px 2px 8px #747474;
                background-image: url("http://goo.gl/7IC8sK");/*If You want image background*/
                background-size: contain;                     /*If You want image background*/
                background-repeat: repeat-x;                  /*If You want image background*/
            }
            
            #days:after,#hours:after,#minutes:after,#seconds:after{
                
                font-size: 14px;
                line-height:normal;
                display: block;
                width: inherit;
                margin-top: 10px;
                color: #5C5757;
                text-align: center;
            }
            #days:after{
                content: "Days";
            }
            #minutes:after{
                content: "Minutes";
            }
            #hours:after{
                content: "Hours";
            }
            #seconds:after{
                content: "Seconds";
            }
working Demo,
Time Remaining for :

00 00 00 00

11 Mar 2014

Simple Blogger 'related posts' widget

In today's post I will be explaining 'How to use Related posts widget in your blogger blog ?'.This widget will be helpful in displaying links to related posts beneath each post.

This widget chooses related posts based on their 'Label'.


Type 1. Related posts with thumbnail



Code for this widget,
<!-- Related posts starts-->
    
<script src='https://sites.google.com/site/curiohub/home/related/Related_posts2.js' type='text/javascript'/>

<link href='https://sites.google.com/site/curiohub/home/related/related_css2.css' rel='stylesheet' type='text/css'/>

<b:if cond='data:blog.pageType == &quot;item&quot;'>

      <b:loop values='data:post.labels' var='label'><b:if cond='data:blog.pageType == &quot;item&quot;'>

<script expr:src='&quot;/feeds/posts/default/-/&quot; + data:label.name + &quot;?alt=json-in-script&amp;callback=related_results_labels&amp;max-results=5&quot;' type='text/javascript'/></b:if></b:loop>

<script type='text/javascript'> var href = &quot;<data:post.url/>&quot;;
                                var currentposturl = href.substr(href.lastIndexOf(&#39;/&#39;) + 1);
                                removeRelatedDuplicates(); printRelatedLabels(currentposturl);
</script>
</b:if>


<!-- Related posts ends -->

Type 2. Related posts without thumbnail 




Code for it,
<!-- Related posts widget starts-->
<script src='https://sites.google.com/site/curiohub/home/related/Related_posts.js' type='text/javascript'/>

<b:if cond='data:blog.pageType == &quot;item&quot;'>

   <b:loop values='data:post.labels' var='label'><b:if cond='data:blog.pageType == &quot;item&quot;'>

 <script expr:src='&quot;/feeds/posts/default/-/&quot; + data:label.name + &quot;?alt=json-in-script&amp;callback=related_results_labels&amp;max-results=5&quot;' type='text/javascript'/></b:if></b:loop>

<script type='text/javascript'> var href = &quot;<data:post.url/>&quot;;
        var currentposturl = href.substr(href.lastIndexOf(&#39;/&#39;) + 1);
        removeRelatedDuplicates(); printRelatedLabels(currentposturl);
</script>
</b:if>

<!-- Related posts widget ends-->

How to use Above code in blogger

Follow below given steps to integrate above code in your blog,
1. Copy Any of above code.
2. Go to Template -> Edit HTML in your Blogger Dashboard.
3. Search for end of post, i.e. search for <data:post.body/> [Last one] 
4. Paste the copied copy just beneath the code you just searched for.
5. Now save your Template and You are done.

Customization:
For changing maximum number of related links change the number '5' to any desired number,in code highlighted with red color, max-results=5


If you are getting any problem in implementing this widget, please leave a comment I will be happy to help.

13 Jan 2013

creating image stacking using css

Today i will show you how to create a Image stack using pure css3 technique.
So, without further delay, here we go.
Here i using css pseudo-elements to create a stacking effect.
    <div id="stack1"></div>
    <div id="stack2"></div>
I am going to apply stacking effect on above DIV's, you can use an image or anything else in place of these DIV's.
/* styling div's*/
#stack1,#stack2{
                        display: block;
                        width: 180px;
                        height: 200px;
                        border: 10px solid #fff;
                        box-shadow:0px 0px 10px #000;
                        position: relative;
                        background: #000;
                        float: left;
                        margin-top: 50px;
                        margin-left: 50px;
                    }
Now below is CSS for stackig effect
 /* for type 1 stacking*/
                    #stack1:before,#stack1:after{
                        z-index:-1;
                        display: block;
                        position: absolute;
                        width: 100%;
                        height:100%;
                        background: #FFF;
                        content: "";
                        border: 10px solid #fff;
                        padding: 0px;
                        margin: 0px;
                        top: -10px;
                       left: -8px;
                       
                       box-shadow:0px 0px 10px #000;
                       -webkit-box-shadow:0px 0px 10px #000;
                    }
                    #stack1:before{
                         -moz-transform:rotate(4deg);
                         -webkit-transform:rotate(4deg);
                    }
                    #stack1:after{
                        z-index:-2;
                         -moz-transform:rotate(8deg);
                         -webkit-transform:rotate(8deg);
                    }
                    /* for type 2 stacking*/
                    #stack2:before,#stack2:after{
                        z-index:-1;
                        display: block;
                        position: absolute;
                        width: 100%;
                        height:100%;
                        background: #FFF;
                        content: "";
                        border: 10px solid #fff;
                        padding: 0px;
                        margin: 0px;
                        top: 0px;
                        left: -3px;
                       
                       box-shadow:0px 0px 10px #000;
                        -webkit-box-shadow:0px 0px 10px #000;
                    }
                    #stack2:after{
                        z-index:-2;
                        top: 10px;
                        left:6px;
                    }
Result

Click for Live Demo

6 Oct 2012

Count number of rows returned in Mysql with LIMIT Clause

Knowledge of total number of rows returned from a MySql Query is very important for pagination purpose.
But it becomes difficult to count total number of rows with "LIMIT" clause. Solution to this problem is to use "SQL_CALC_FOUND_ROWS" function which helps in getting results quickly.

Today i will show you, how to use "SQL_CALC_FOUND_ROWS" function. below is a sample code, you can see the query structure
    $query = mysql_query("select SQL_CALC_FOUND_ROWS id from book  LIMIT 0,10");
    $rows = mysql_query("SELECT FOUND_ROWS() AS `found_rows`");

Now check the result as follows
    while($res1 = mysql_fetch_assoc($query))
    {
     echo $res1['id'].'<br/>'; 
    }
    
    print_r(mysql_fetch_assoc($rows));
    

The result,
51
52
53
54
55
56
57
58
59
60
Array
(
    [found_rows] => 67
)

SQL_CALC_FOUND_ROWS and Problem with Codeigniter

"SQL_CALC_FOUND_ROWS" function does not work in codeigniter. So total number of rows returned can be counted as follows.
Here i am using codeigniter's "Active Record Caching" to avoid writing same code twice.
$this->db->start_cache();
    $this->db->select('b.*, u.username');
    $this->db->from('book b');
    $this->db->join('users u', 'b.userid = u.id');
    $this->db->where('b.cat', 'science');
$this->db->stop_cache();

$totalRows = $this->db->count_all_results();


$this->db->limit(20);

$query = $this->db->get();
$data->books = $query->result();

$this->db->flush_cache();

echo $totalRows;


2 Oct 2012

building simple php pagination script in 10 steps

Pagination is simply a process of dividing your output contents in small modules and displaying them on different pages.
For example,you can see Google search results where 10 to 15 search results are shown per page.
Pagination make output more user friendly.

Process for creating pagination script in 10 steps:

Today i'll develop pagination script in 10 easy steps.So let's get started, first of all Create two php files, 
  1.  pagination.php (for connection with Database and calculation) 
  2.  index.php        (for pagination display)
Note: I will be using 'pagination' as database name and 'data' as table name, change it according to your database and table name. 
Step 1: Open Pagination.php file in any of your favourite text editor and connect to database
<!-------------------------pagination.php --------->
<?php
 // connect to mysql//
//step:1

$con = mysql_connect("localhost","root",""); // Enter hostname,user,password 
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  // select database
  mysql_select_db("pagination", $con); //Provide database name which has our data for pagination.
  
Step 2: Count number of rows in table
//   count total number of rows from the desired table in the database  //
//step:2
    
  $query = mysql_query("SELECT * FROM data"); //Counting total number of rows in the table 'data',
  $total_rows = mysql_num_rows($query);
Step 3: Setup configuration
// setup configuration//  
//step:3

  $base_url = 'https://localhost/pagi/';    //Provide location of you index file  
  $per_page = 10;                           //number of results to shown per page 
  $num_links = 8;                           // how many links you want to show
  $total_rows = $total_rows; 
  $cur_page = 1;                           // set default current page to 1
Step 4: Extract information from url,when request made through pagination links
//now we will extract information from url//
//step:4
    if(isset($_GET['page']))
    {
      $cur_page = $_GET['page'];
      $cur_page = ($cur_page < 1)? 1 : $cur_page;            //if page no. in url is less then 1 or -ve
    }
Step 5: Calculate limit and offset for Querying Table
// calculate limit and offset, it'll will be used for Sql Query//
//step:5
    $offset = ($cur_page-1)*$per_page;                //setting offset
   
    $pages = ceil($total_rows/$per_page);              // no of page to be created
Step 6: Calculating the start and end page numbers for pagination links
//Calculate the start and end page numbers for pagination links//
//step:6

    $start = (($cur_page - $num_links) > 0) ? ($cur_page - ($num_links - 1)) : 1;
    $end   = (($cur_page + $num_links) < $pages) ? ($cur_page + $num_links) : $pages;
Step 7: Query the Database for displaying only 10 ['$per_page'] item per page.
//query the database with calculated OFFSET //
//step:7
    $res = mysql_query("SELECT * FROM data LIMIT ".$per_page." OFFSET ".$offset);

 mysql_close($con);
 
 // pagination.php completed // 
?>
Till now we have completed our work on pagination.php next we will work on index.php, As follows.
Step 8: Display the results in index.php
In this example table 'data' has id,title and content field , so I am going to display them as follows.
<!-- Now We are in index.php ---->
<!DOCTYPE html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="eng">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Pagination</title>

    </head>
    <body>    
    <?php
 
    include("pagination.php"); // DON'T FORGET THIS

     //        display the results //
     //step:8
     
        if(isset($res))// results from Step 7
        {
            //creating table
            echo '<table style="width:600px; cell-padding:4px; cell-spacing:0; margin:auto;">';           echo'<th>id</th><th>title</th><th>content</th></tr>'; 
            while($result = mysql_fetch_assoc($res))
            {
              echo '<tr>';
              echo '<td>'.$result['id'].'</td>'.'<td>'.$result['title'].'</td>'.'<td>'.$result['content'].'</td>' ;
              echo '</tr>';
            }
            echo '</table>';
        }
    ?>
Step 9: Display Pagination Page Numbers
<!--//display pagination page numbers //
    //step:9 
    -->
    <div id="pagination">
        <div id="pagiCount">
            <?php
                if(isset($pages))
                {  
                    if($pages > 1)        
                    {    if($cur_page > $num_links)     // for taking to page 1 //
                        {   $dir = "first";
                            echo '<span id="prev"> <a href="'.$_SERVER['PHP_SELF'].'?page='.(1).'">'.$dir.'</a> </span>';
                        }
                       if($cur_page > 1) 
                        {
                            $dir = "prev";
                            echo '<span id="prev"> <a href="'.$_SERVER['PHP_SELF'].'?page='.($cur_page-1).'">'.$dir.'</a> </span>';
                        }                 
                        
                        for($x=$start ; $x<=$end ;$x++)
                        {
                            
                            echo ($x == $cur_page) ? '<strong>'.$x.'</strong> ':'<a href="'.$_SERVER['PHP_SELF'].'?page='.$x.'">'.$x.'</a> ';
                        }
                        if($cur_page < $pages )
                        {   $dir = "next";
                            echo '<span id="next"> <a href="'.$_SERVER['PHP_SELF'].'?page='.($cur_page+1).'">'.$dir.'</a> </span>';
                        }
                        if($cur_page < ($pages-$num_links) )
                        {   $dir = "last";
                       
                            echo '<a href="'.$_SERVER['PHP_SELF'].'?page='.$pages.'">'.$dir.'</a> '; 
                        }   
                    }
                }
            ?>
        </div>
    </div>
   
</body>
</html>
Step 10: Finally Add some css in the <head></head> section of index.php Change this CSS as it pleases you.
<!DOCTYPE html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="eng">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Pagination</title>
        
        <style type="text/css">
            /* Double Click to Copy and paste Style in <head></head> of index.php */ 
            #pagination {
                display: block;
                text-align: center;
            }
            #pagiCount{
                display: inline-block;
                margin: auto;
            }
            #pagiCount a, #pagiCount strong {
                display: block;
                width: 50px;
                background: rgb(0, 53, 148);
                float: left;
                margin-right: 5px;
                color: #fff;
                text-align: center;
                text-decoration: none;
                font-size:20px;
                line-height: 29px;
            }
            #pagination strong , #pagination a:hover {
                background:rgb(130, 171, 245);
                color:#000;
                font-size:22px;
            }
            tr:nth-child(even) {
                background: #CCC
            }
        </style>
And finally our pagination script is ready to use.
Download Pagination Database used in above code and import in your phpMyAdmin for experimenting purpose