views:

155

answers:

4

Hi. 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 it?

+1  A: 

Use the LIMIT clausule of the query to limit the amount of results you retrieve from the database.

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

Rody van Sambeek
Can you put an example for the PHP code, please?
Francesc
Google is your friend: http://www.phpeasystep.com/phptu/29.html
Rody van Sambeek
+1  A: 

Use LIMIT.

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

40 is how many records to skip, 10 is how many to display.

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

Mark Byers
There is nothing intrinsically wrong with using string concatenation to build an sql query if the data is known to be safe.
code_burgar
@code_burgar: It won't give the wrong result, but it will result in a new query plan for every new set of parameters. You should use bind parameters.
Mark Byers
A: 

I'd start by Googling a bit. There is no lack of information on this subject out there.
(It's a pretty common question.)

Atli
You can down-vote me all you want... but you know I'm right :)
Atli
I didn't down-vote you.
Francesc
+4  A: 

Here is a nice 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
code_burgar
But, How I can create the links to the others pages?
Francesc
Select COUNT for all results matching your where clause, divide the number you get by your perPage value and you get the total number of pages, then just do a for loop to echo links to each page.
code_burgar
But for the previous one? Can you put an example please? I'm a newvie.Thanks
Francesc
there you go, you should really be able to take it from there
code_burgar