Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - MySQL query with Pagination

How would I go about making a pagination script for this MySQL & PHP query.

if (isset($_GET['c'])) {
$c = $_GET['c'];
}

$query = mysql_query("SELECT * FROM Categories WHERE category = '$c' ");

        WHILE($datarows = mysql_fetch_array($query)):

        $id = $datarows['id'];
        $category = $datarows['category'];
        $code = $datarows['code'];

        endwhile;

$query2 = mysql_query("SELECT * FROM Games WHERE category = '$code' ");

WHILE($datarows_cat = mysql_fetch_array($query2)):

        $title = $datarows_cat['title'];
        $description = $datarows_cat['description'];
        $imgurl = $datarows_cat['image_name'];
        $category = $datarows_cat['category'];
        $views = $datarows_cat['view_count'];
        $pagename = $datarows_cat['pagename'];
                $featured = $datarows_cat['featured'];

if ($featured =="1") {$f = "<img src='http://my-site.com/images/star.png' width='13px' title='Featured Game' /> Featured"; } else {$f = "";}
                    if(is_int($views/2)) {
$views = $views / 2;
} else { $views = $views / 2 + .5; }

if (strlen($description) > 95) {
    $desc= substr($description,0,95);
    $desmod = "$desc...<br/><a href=\"http://my-site.com/$pagename#1\" title=\"$description\">- Read More</a>";
    }
else {$desmod = "$description";}

        echo "$f - <a href=\"http://my-site.com/$pagename\">$title - $desmod</a><br/>";

endwhile;

And when I visit http://my-site.com/categories/Action for instance, The code looks up that category in my category table, then once it gets the unique code for that category, It runs another query to find all games in another table with that category code. Currently, however, I have 200+ games loading for a single category which causes a great amount of loading time.

Thanks for your help!


1 Answers

First of all find out how many games are there for a specific category

change the line

$query2 = mysql_query("SELECT * FROM Games WHERE category = '$code' ");

to

$sql="SELECT * FROM Games WHERE category = '$code' ";
$query_count=mysql_query($sql);

Add following after it

$per_page =30;//define how many games for a page
$count = mysql_num_rows($query_count);
$pages = ceil($count/$per_page);

if($_GET['page']==""){
$page="1";
}else{
$page=$_GET['page'];
}
$start    = ($page - 1) * $per_page;
$sql     = $sql." LIMIT $start,$per_page";
$query2=mysql_query($sql);

Then display the numbers of pages where you want

<ul id="pagination">
        <?php
        //Show page links
        for ($i = 1; $i <= $pages; $i++)
          {?>
          <li id="<?php echo $i;?>"><a href="linktoyourfile?c=<?php echo $c;?>&page=<?php echo $i;?>"><?php echo $i;?></a></li>
          <?php           
          }
        ?>
      </ul>

Use CSS for pagination this will do the trick

like image 63
vinu Avatar answered Sep 20 '25 09:09

vinu