Jump to content

Problem with pagination


Ex1t

Recommended Posts

This is my code for pagination

<?php 

      $sql = "SELECT * FROM images"; 
      $rs_result = mysqli_query($con, $sql);
      $total_records = mysqli_num_rows($rs_result);
      $total_pages = ceil($total_records / $end); 

      echo "<a href='index.php?page=1'><button>".'First page'."</button></a>  "; 

      for ($i=1; $i<=$total_pages; $i++) { 
                  echo "<a href='index.php?page=".$i."'><button>".$i."</button></a> "; 
      }; 
      echo " <a href='index.php?page=$total_pages'><button >".'Last page'."</button></a>";

?>

Its works, but the display will be as follows

lPx12fk.png
But i want something like this
aoX8pyy.png

How to create that dots? Something like a max pagination pages.. If u know what I mean.. Because i will have more than 20 pages on my website and it will spoiling the design
 

Link to comment
Share on other sites

Do you mean you want to have a page range? If so check out our pagination tutorial (note needs updating to use mysqli).

 

Example

$currentpage = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 20;

$sql = "SELECT * FROM images"; 
$rs_result = mysqli_query($con, $sql);
$total_records = mysqli_num_rows($rs_result);

$total_pages = ceil($total_records / $results_per_page); 

// range of num links to show
$range = 3;

echo "<a href='index.php?page=1'><button>First page</button></a>  ";

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range)  + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $total_pages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " <b>$x</b> ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='index.php?page=$x'><button>$x</button></a> ";
      } // end else
   } // end if 
} // end for

echo "  <a href='index.php?page=$total_pages'><button >Last page</button></a>";
Link to comment
Share on other sites

Here's a demo page of how I handle it. Sample output attached

$page = isset($_GET['page']) ? $_GET['page'] : 1;

$totalPages = 20;

function pageNav ($page, $total)
        {
            $str = 'Pages ';
            if ($total < 11)
            {
                for ($p=1; $p <= $total; $p++)
                {
                    $class = $page==$p ? 'nolink' : 'link';
                    $str .= "<div class='nav $class'>$p</div>";
                }
            }
            else
            {
                $class = $page==1 ? 'nolink' : 'link';
                $str .= "<div class='nav $class'>1</div>";
                if ($page < 5)
                {
                    $p1 = 2;
                    $p2 = 6;
                }
                else
                {
                    $p1 = min ($page-2, $total-5);
                    $p2 = min ($page+2, $total);
                    $str .= '... ';
                }
                for ($p=$p1; $p <= $p2; $p++)
                {
                    $class = $page==$p ? 'nolink' : 'link';
                    $str .=  "<div class='nav $class'>$p</div>";
                }
                if ($total-$page > 3) $str .= '... ';
                $class = $page==$total ? 'nolink' : 'link';
                if ($total > $page+2) $str .= "<div class='nav $class'>$total</div>";
            }
            return $str;
        }

?>
<html>
<head>
<title>Page Nav</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    $().ready(function() {
        $(".link").click(function() {
            var pgnum = $(this).html();
            location.href = "?page="+pgnum; // specify action on click of page number here
        })
    })
</script>
<style type="text/css">
div.nav {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 5px;
    padding: 0;
    text-align: center;
    font-family: sans-serif;
    font-size: 9pt;
}
div.link {
    border: 1px solid blue;
}
div.nolink {
    font-weight: 700;
    border: none;
}
</style>
</head>
<body>
    <h1>This is page <?=$page?></h1>
    <?=pageNav($page, $totalPages)?>
</body>
</html>

post-3105-0-72647300-1438607107_thumb.png

  • Like 1
Link to comment
Share on other sites

Here's an example

<?php
session_start();
include("db_inc.php");  // defines HOST, USERNAME and PASSWORD
try {
    $db = new mysqli(HOST,USERNAME,PASSWORD,'test');
} catch(Exception $e) {
    die("DB connection error");
}

$perPage = 30;  // set how many records to display on each page

if (!isset($_SESSION['pages'])) {
    // count records to determine how many pages
    $sql = "SELECT COUNT(*) FROM restaurant";
    $res = $db->query($sql);
    list($numrecs) = $res->fetch_row();
    $_SESSION['pages'] = ceil($numrecs/$perPage);
}

$totalPages = $_SESSION['pages'];

// get current page number
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// calculate offset for query LIMIT clause
$offset = ($page - 1) * $perPage;

// select the next perPage records
$sql = "SELECT restaurant_name
        FROM restaurant
        ORDER BY restaurant_name
        LIMIT $offset, $perPage";

$res = $db->query($sql);
$output = '';
while ($row = $res->fetch_assoc()) {
    $output .= $row['restaurant_name'] . '<br>';
}


function pageNav ($page, $total)
{
    $str = 'Pages ';
    if ($total < 11)
    {
        for ($p=1; $p <= $total; $p++)
        {
            $class = $page==$p ? 'nolink' : 'link';
            $str .= "<div class='nav $class'>$p</div>";
        }
    }
    else
    {
        $class = $page==1 ? 'nolink' : 'link';
        $str .= "<div class='nav $class'>1</div>";
        if ($page < 5)
        {
            $p1 = 2;
            $p2 = 6;
        }
        else
        {
            $p1 = min ($page-2, $total-5);
            $p2 = min ($page+2, $total);
            $str .= '... ';
        }
        for ($p=$p1; $p <= $p2; $p++)
        {
            $class = $page==$p ? 'nolink' : 'link';
            $str .=  "<div class='nav $class'>$p</div>";
        }
        if ($total-$page > 3) $str .= '... ';
        $class = $page==$total ? 'nolink' : 'link';
        if ($total > $page+2) $str .= "<div class='nav $class'>$total</div>";
    }
    return $str;
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Pagination Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    $().ready(function() {
        $(".link").click(function() {
            var pgnum = $(this).html();
            location.href = "?page="+pgnum; // specify action on click of page number here
        })
    })
</script>
<style type="text/css">
div.nav {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 5px;
    padding: 0;
    text-align: center;
    font-family: sans-serif;
    font-size: 9pt;
}
div.link {
    border: 1px solid blue;
    cursor: pointer;
}
div.nolink {
    font-weight: 700;
    border: none;
}
div#rests {
    font-family: sans-serif;
    font-size: 12pt;
    padding: 20px;
    color: #AA16B6;
    width: 400px;
    margin-top: 20px;
    margin-bottom: 20px;
    margin-left: auto;
    margin-right: auto;
    border-top: 1px solid gray;
    border-bottom: 1px solid gray;
}
div.pagenums {
    text-align: center;
}
</style>
</head>
<body>
    <h1>Restaurants</h1>
    <div class='pagenums'>
        <?=pageNav($page, $totalPages)?>
    </div>
    <div id='rests'>
        <?=$output?>
    </div>
    <div class='pagenums'>
        <?=pageNav($page, $totalPages)?>
    </div>
</body>
</html>

Link to comment
Share on other sites

@Barand, Really helpful, Thank you very much.

 

I need to change these lines

<?=pageNav($page, $totalPages)?>

to

<?php echo pageNav($page, $totalPages); ?>

Can you tell what is the problem of it? is it php version?

Link to comment
Share on other sites

 

is it php version?

Yes and no.

 

If you are using PHP version 5.4 or newer then that short hand php echo tag should work. For older older versions of PHP you can enabled a setting short_open_tag in the php.ini (or via ini_set during runtime) to allow you to use short hand php syntax.

Edited by Ch0cu3r
Link to comment
Share on other sites

@Barand, one more question.

 

I need to display a string something like below using above pagination script.

Showing 1 - 6 of 19 items

I can display number of items but not sure how to display result range.

 

This is how I tried it.

Showing <?=$page - $offset?> of <?=$numrecs?> items     

Thanks

Link to comment
Share on other sites

Simple arithmetic

// select the next perPage records
$sql = "SELECT restaurant_name
        FROM restaurant
        ORDER BY restaurant_name
        LIMIT $offset, $perPage";
$res = $db->query($sql);

$recs = $res->num_rows;
$p = ($page - 1) * $perPage + 1;
$q = $p + $recs - 1;

$output = "Showing items $p to $q of $numrecs<br><br>";
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.