user5060975
user5060975

Reputation:

Pagination Prev - Next Increment

i create a php news system, but i have a problem:

<?php
include('config.php');
if( isset( $_GET["page"]) ) $PAGE=$_GET["page"]; else $PAGE=1;
$query1=mysql_query("select id, name, email , age from addd LIMIT ". (($PAGE * 5) - 5) .",5");

echo "<table><tr><td>Testo</td><td>Nome</td><td>Anni</td></tr>";

function truncate_string($str, $length) {
if (!(strlen($query2['name']) <= $length)) {
    $query2['name'] = substr($query2['name'], 0, strpos($query2['name'], ' ', $length)) . '...';
}

return $query2['name'];
}

while($query2=mysql_fetch_array($query1))
{
$number= $query2['name'];
echo "<tr><td>".substr($query2['name'], 0, 500)."...</td>";
echo "<td>".$query2['email']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td>".str_word_count($number)."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Mod</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."' onclick=\"return confirm('Sei sicuro di volerlo eliminare?');\");'>Canc</a></td><tr>";
echo "<td><a href='singletwo.php?id=".$query2['id']."');'>vedi</a></td<tr>";
}
?>

The pages follow this numbering: ?page=1, ?page=2 ecc.

Each page contains 5 news.

How do I create an automatic pagination system?

With Prev-Next, automatically detect possible next or previous pages?

I don't know how to do it.

Upvotes: 0

Views: 1259

Answers (2)

Peter
Peter

Reputation: 9113

What you could do is:

$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = $currentPage*5;
$offset = $offset-5;

Now that you have these numbers, you can use them in your query:

$stmt = "SELECT
...
FROM news
LIMIT ".$offset.", ".$limit.";

This way you'll get the records you want. As far as the next and previous buttons go:

if ($currentPage > 1) {
    // Show previous button
}

For the next button you'll need to do another query:

$stmt = "SELECT COUNT(*) as total FROM news";
$result = $pdo->fetch();
$totalRows = $result['total'];

if ($currentPage < round($totalRows/5)) {
    // Show next button
}

Upvotes: 0

user2366822
user2366822

Reputation:

Start by having the max length and total number of rows in variables:

<?php
include('config.php');

$max = 5;
$total = mysql_query("select count(*) from addd");
$PAGE = isset($_GET["page"]) ? $_GET["page"] : 1;

$query1 = mysql_query("select id, name, email , age from addd LIMIT " . (($PAGE * $max) - $max) . "," . $max);

That way, you can calculate how many pages you'll need.

The following code will give you a page list (Page 1, Page 2, Page 3 etc.):

for($i = 0; $i < ceil($total / $max); $i ++)
{
    $p = $i + 1;
    echo '<a href="?page=' . $p . '">Page ' . $p . '</a>';
}

If you'd rather have Previous and Next links, try this:

if($PAGE > 1)
    echo '<a href="?page=' . ($PAGE - 1) . '>Previous</a>';

if(ceil($total / $max) > $PAGE)
    echo '<a href="?page=' . ($PAGE + 1) . '>Next</a>';

Upvotes: 1

Related Questions