Unidan Unidan - 1 year ago 47
PHP Question

limit number of posts in single page

I wanna limit number of posts on page. Here is code i am using :-

<?php
$query="select * from namedb";
$result=mysqli_query($connect,$query);
while($r=mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $r['title']?></td>
<td><?php echo $r['comment']?></td>
<td><?php echo $r['cgender']?></td>
<td><?php echo $r['cnumerology']?></td>
<td><?php echo $r['creligion']?></td>
</tr>
<?php } ?>


and using this code for pagination

<?php
$query="select * from namedb";
$result=mysqli_query($connect,$query);
$count=mysqli_num_rows($result);
$pages=ceil($count/10);
for($i=1;$i<=$pages;$i++) { ?>
<a href="links.php?p=<?php echo $i; ?>">
<?php echo $i;?></a>
<?php } ?>


There are 21 posts in my database and 20 posts are showing on my page but pagination is showing as 1 2 3 and 2nd & 3rd page is showing same data. how to fix it.

I wanna show 30 records per page and if page has less then 30 records then pagination will not show.

Answer Source

There is nothing in your code that actually does any paging when you get the names from the database. Change the first part to the following code and keep the 2nd part of the code same.

$page = 1;
$per_page = 10;
if(isset($_GET['p']) && is_numeric($_GET['p']) )
    $page= $_GET['p'];
$offset = ($page -1) * $per_page;

$query="select * from namedb LIMIT $offset, $per_page  ";
$result=mysqli_query($connect,$query);
while($r=mysqli_fetch_assoc($result))
{ ?>
    <tr>
    <td><?php echo $r['title']?></td>
    <td><?php echo $r['comment']?></td>
    <td><?php echo $r['cgender']?></td>
    <td><?php echo $r['cnumerology']?></td>
    <td><?php echo $r['creligion']?></td>
    </tr>
<?php } ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download