Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & MySQL Pagination

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?

like image 597
Francesc Avatar asked Apr 11 '10 10:04

Francesc


People also ask

What PHP stand for?

PHP, originally derived from Personal Home Page Tools, now stands for PHP: Hypertext Preprocessor, which the PHP FAQ describes as a "recursive acronym." PHP executes on the server, while a comparable alternative, JavaScript, executes on the client.

Is PHP better than JavaScript?

Since we can handle both front-end and back-end through Javascript now, It's considered as more powerful than PHP. JavaScript: It is the most popular lightweight, interpreted compiled programming language. It is also known as a scripting language for web pages.

What is PHP or HTML?

PHP is used for server-side programming which will interact with databases to retrieve information, storing, email sending, and provides content to HTML pages to display on the screen. HTML is used for specifying colors, text formatting, aligning, etc. PHP is easy to learn but not as much as HTML.

Is PHP a programming?

PHP is an open-source, server-side programming language that can be used to create websites, applications, customer relationship management systems and more. It is a widely-used general-purpose language that can be embedded into HTML.


2 Answers

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
like image 122
code_burgar Avatar answered Sep 29 '22 18:09

code_burgar


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.

like image 20
Mark Byers Avatar answered Sep 29 '22 20:09

Mark Byers