Gamer Gamer -3 years ago 65
MySQL Question

Pagination in PHP during passing a value at the first time when the page loads

This is a simple code which I am using in PHP. But the problem is every time I run the page, it says undefined index page. But after clicking a href link, it works perfectly. Can anyone help me out how to resolve the error?

Actually the

$_GET['page']
isn't having a value at the first time when the page loads. But I need this to execute the query to take out data from the database. Here's the code:

<?php

require 'db_connect.php';

$page=$_GET["page"];
if($page=="" || $page=="1") {
$page1=0;
} else {
$page1=($page*5)-5;
}


$sql="SELECT * FROM tbl_product WHERE deletion_status=1 limit $page1,5";
$res=mysqli_query($db_connect,$sql);

while($row=mysqli_fetch_assoc($res)) {
echo $row['product_id']." ".$row['product_name'];
echo "<br>";
}

$sql1="SELECT * FROM tbl_product WHERE deletion_status=1";
$res1=mysqli_query($db_connect,$sql1);
$count=mysqli_num_rows($res1);
echo'<br>';
//echo $count;
$a=$count/5;
echo'<br>';
$a=ceil($a);

for($b=1;$b<=$a;$b++){
?><a href="pagination2.php?page=<?php echo $b;?>" style="text-decoration: none;"><?php echo " "; echo $b;?></a><?php
}
?>

Answer Source

Before trying to use the value, check if it exists:

$page = "1";
if (isset($_GET["page"])) {
    $page = $_GET["page"];
}

That way it's initialized with a default value, but if a value has been provided it will use that one instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download