Backend Development

Pagination

Submitted by linkzy, , Thread ID: 22382

Thread Closed

RE: Pagination

#8
There might be errors since I did not test it, but this should give you an idea.

Code:
<?php

// 30 Users per page
define( 'PER_PAGE', 30 );

$page  = intval( $_GET['page'] );

/**
* When $page = 1: $start = ( 1 - 1 ) * 30 = 0
* When $page = 2: $start = ( 2 - 1 ) * 30 = 30
* When $page = 3: $start = ( 3 - 1 ) * 30 = 60
* ...
*/
$start = ( $page - 1 ) * PER_PAGE;

$numUsers = mysql_fetch_field( mysql_query( 'SELECT COUNT(*) AS count FROM users' ), 'count' );
$totalPages = ( PER_PAGE > $numUsers ) ? 1 : ceil( (float)$numUsers / PER_PAGE );

$pagination = '';
for( $i = 0; $i < $totalPages; $i++ )
{
$pagination .= '<a href="index.php?page='.($i+1).'">Page '.($i+1).'</a>';
}

?>

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body style="background: #d2d2d2;">
<center><h1>User List</h1></center>
<table>
<tr>
<th>Name</th>
<th>Cash</th>
<th>Score</th>

<?php
require_once './config.php';

$query = mysql_query( sprintf( 'SELECT `name`, `cash`, `score` FROM `users` LIMIT %d, %d', $start, PER_PAGE ) );

while( $row = mysql_fetch_array($query) )
{
?>
<tr>
    <td class="left"><?php echo $row['Name']; ?></td>
    <td class="left"><?php echo $row['Cash']; ?></td>
    <td class="left"><?php echo $row['Score']; ?></td>
</tr>
<?php
}
?>

</table>
</body>
</html>
Do not let your difficulties fill you with anxiety, after all it is only in the darkest nights that stars shine more brightly. - Ali(a.s)

Developer( PHP, Python, C++, HTML+CSS, JS I am available for Hire. Message Me for details.


Users browsing this thread: 4 Guest(s)