Setting up PHP and MySQL pages

I have a MySQL query

SELECT * FROM 'redirect'
WHERE 'user_id'= \''.$_SESSION['user_id'].' \' 
ORDER BY 'timestamp'`

I want to paginate 10 results per page. How can i do this?

+3
source share
4 answers

Here is a good starting point:

<?php

// insert your mysql connection code here

$perPage = 10;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);

$query = "SELECT COUNT(*) as total FROM redirect
WHERE user_id = '".$_SESSION['user_id']."'";
$r = mysql_fetch_assoc(mysql_query($query));

$totalPages = ceil($r['total'] / $perPage);

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


$r = mysql_query($query);

$query = "SELECT * FROM 'redirect'
WHERE 'user_id'= \''.$_SESSION['user_id'].' \' 
ORDER BY 'timestamp' LIMIT $startAt, $perPage";

$r = mysql_query($query);

// display results here the way you want

echo $links; // show links to other pages
+13
source

Use LIMIT .

SELECT *
FROM redirect
WHERE user_id = '35251' 
ORDER BY timestamp
LIMIT 40, 10

40 - how many records to skip, 10 - how many are displayed.

There are also a few problems with your PHP. You use backticks (not single quotes) to surround table and column names. And you should not use string concatenation to create a query.

+4
source

Use the LIMIT query clause to limit the number of results that you retrieve from the database.

See: http://dev.mysql.com/doc/refman/5.1/en/select.html

+1
source

I would start with googling a bit. There is no shortage of information on this.
(This is a fairly common question.)

-1
source

Source: https://habr.com/ru/post/1740649/


All Articles