Pagination with PDO and MySQL - php

Im trying to return all records from my database and paginate them accordingly,
I have the following I've managed to wrangle together from a tutorial only It doesnt seem to output anything to my browser so I presume I've made an error in my syntax?
// No County Selected
try
{
$per_page = '3';
$res = $conn->prepare("SELECT * FROM directory WHERE user_active != ''");
$rows = $res ->fetchAll();
$total_records = count($rows);
$pages = ceil($total_records / $per_page);
$page = (isset ($_GET['page'])) ? (int) $_GET['page'] : 1 ;
$start = ($page - 1) * $per_page;
$query = $db->query("SELECT * FROM directory LIMIT $start , $per_page");
while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo '<br>' . $row['id'];
} ?>
<br><br>
<?php
if ($pages >= 1 && $page <= $pages){
//if ($page>1 && $page <= $pages){$previous=($page -1); echo 'Previous';}
for($x=1; $x<=$pages; $x++){ echo ($x == $page) ? ' <strong>'.$x.'</strong> ' : ' '.$x.' ';}
//if ($page>1 && $page <= $pages){ $next=($page+1) ; echo 'Next';}
}

You have a logical flaw in your queries. The condition mismatches between the query you use to obtain the total count:
SELECT * FROM directory WHERE user_active != ''
and the query you use to fetch the limited (paginated) rows:
SELECT * FROM directory LIMIT $start , $per_page
Both queries should share the same conditions. Additionally, the first query should only COUNT the rows, not return them all:
SELECT COUNT(1) FROM directory WHERE user_active != ''
You will then find the number of rows (count) in the first column of the first result-row.

Related

How to make query switch variables if row not found in php and sql

I have a form for real estate search and the first field should be able to return result based on 3 fields in the database. if by hood returns 0 then it should search by city else search by country
<?php
//search value
$location=$_GET["location"];
$type=$_GET['type'];
$price=$_GET['price'];
//==================================================================
#variables of search query
// User input
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 6;
// Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
// Query
$articles = "
SELECT SQL_CALC_FOUND_ROWS property_id, title,bedrooms,images,owner,status,posted_by,gsize,city,price,post_date,location,currency,poster_id
FROM properties where location='$location' or city='$location' or hood='$location'
";
if($type && !empty($type)){
$articles .= " AND property_type='$type'";
}
if($price && !empty($price)){
$articles .=" AND price <= '$price'";
}
$articles .= " order by post_date desc LIMIT {$start}, {$perPage}";
$articles=$dbc->query($articles);
$articles = $articles->fetchAll(PDO::FETCH_ASSOC);
?>

Php pagination with SQL not working

I have done this pagination using PHP and SQL. Id 11 and 12 is missing in the page 2 module. I can't find out where my mistake is.
Here my source code:
<?php
$per_page = 5;
$rec_count = $row['id'];
$total_pages = ceil($rec_count / $per_page);
if (isset($_GET['page'])) {
$show_page = $_GET['page']; //current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
$start = 0;
$end = $per_page;
}
} else {
$start = 0;
$end = $per_page;
}
$page = intval($_GET['page']);
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
$sql = "SELECT COUNT(Id) AS id FROM [Register].[dbo].[RegisData] WHERE DeleteStatus = 1";
$result = sqlsrv_query($conn,$sql);
$row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC);
$rec_count = $row['id'];
$total_pages = ceil($rec_count / $per_page);
$sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender]
,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City]
,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus]
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row
FROM [Register].[dbo].[RegisData])
a WHERE row between $start and $end
AND DeleteStatus = 1
ORDER BY RegId";
$result = sqlsrv_query($conn,$sql1);
$z = 1;
for ($x=1; $x<=$total_pages; $x++) {
echo $x;
}
?>
the way you did the pagination combined with DeleteStatus = 1 will always create broken and incomplete pages (if you take all the rows between 1 and 5 and row number 4 is DeleteStatus = 0 you will only get 4 rows)
you should use SQL's LIMIT functionality that allows you to select the result row number to start and how many rows to show after the WHERE clause
so try
$page = intval($_GET['page']);
if($page == 0) $page = 1;
$per_page = 5;
$offset = ($page -1) * $per_page;
$sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender]
,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City]
,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus]
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row
FROM [Register].[dbo].[RegisData])
a WHERE DeleteStatus = 1
ORDER BY RegId
LIMIT {$per_page} OFFSET {$offset}";
for more on LIMIT in SQL look at this short explanation: https://www.techonthenet.com/sql/select_limit.php it's really what you're looking for
---EDIT----
since you don't want to use my suggested solution (for unknown reasons) you can try to make this change to your code:
$sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender]
,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City]
,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus]
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row
FROM [Register].[dbo].[RegisData] WHERE DeleteStatus = 1)
a WHERE row between $start and $end
AND DeleteStatus = 1
ORDER BY RegId";
what I did is add the WHERE DeleteStatus = 1 condition to the internal query that numbers the lines, this way your filter should work as expected - although you should use LIMIT
To prevent duplicates (5 appearing both for page 1 and page 2) you should change this if:
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
}
to this:
if ($show_page > 1 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page + 1;
$end = $start + $per_page;
}
again, if you would have used LIMIT this would not be an issue

Pagination script last page

I created php script following the tutorial, but it has a mistake. It displays in the last page information which is in the previous page - it's because $perpage. How can I display only data which wasn't display yet.
EXAMPLE - If I set $perpage to 3 and I have 7 records (named 1,2,3,4,5,6,7) on page one is 1,2,3 on page two is 4,5,6 and on the last page is 5,6,7 (I want to display only record 7)
$query = mysql_query("SELECT ID FROM clanek");
$count = mysql_num_rows($query);
$perpage = 3; // řádků na stránku
$pages_count = ceil($count / $perpage); //celkem stránek zaokrohleno
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$is_first = $page == 1; //první stránka
$is_last = $page == $pages_count;
$prev = max(1, $page - 1);
$next = min($pages_count , $page + 1); /
$data = mysql_query("SELECT DATE_FORMAT(datum_pridani_c,'%d.%m.%Y %H:%i:%s')as datumcas,nazev,kratky_popis,ID FROM clanek ORDER BY datum_pridani_c DESC LIMIT ".($page - 1).", ".$perpage); /
while ($zaznam = mysql_fetch_array($data)) {
//some info her
}
if($pages_count>0) {
if(!$is_first) {
echo '<a class="predchozistranka" href="index.php?page='.$prev.'">Předchozí</a>';
}
echo '<span class="stranka">Stránka '.$page.' / '.$pages_count.'</span>';
if(!$is_last) {
echo '<a class="dalsistranka" href="index.php?page='.$next.'">Další</a>';
}
}
$data = mysql_query("SELECT DATE_FORMAT(datum_pridani_c,'%d.%m.%Y %H:%i:%s')as datumcas,nazev,kratky_popis,ID FROM clanek ORDER BY datum_pridani_c DESC LIMIT ".($page - 1).", ".$perpage);
It has been a while since I have used MySQL but I fired up my Workbench just now and I see that the syntax for LIMIT is LIMIT offset,rowcount. The doc says so too http://dev.mysql.com/doc/refman/5.0/en/select.html
For your query to work then, instead of ($page - 1), $perpage, it should be ($page - 1)*$perpage, $perpage
$query = mysql_query("SELECT ID FROM clanek");
$count = mysql_num_rows($query);
Irrelevant but the above code is highly inefficient for getting the total number of rows. It would be better if you use SELECT count(id) FROM clanek

SQL Server 2008 Pagination PHP

I am trying to display 10 records per page by using ROW_NUMBER function of SQL SERVER 2008.
I think there is something wrong with my query because I only define where to start and where to end displaying records (from 1 to 10), but not the amount of records displayed per page.
As I go to the next page I get no results displayed at all because I don't know how to add $per_page variable to my SQL query properly.
All I want is be able to display the first 10 product IDs on page 1, and once I click on the "next" button, the next 10 product IDs will be displayed, etc.
This is the code that I have right now:
$per_page = 10;
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
if($page<=1)
{
$start = 0;
}
else
{
$start = $page * $per_page - $per_page;
}
$tsql = " SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY productID) AS
rownum, productID FROM products) AS products1
WHERE rownum >= $start AND rownum <= $per_page";
$num_rows = sqlsrv_num_rows(sqlsrv_query($conn,$tsql));
$num_pages = ceil($num_rows / $per_page);
$stmt = sqlsrv_query($conn,$tsql);
while($row = sqlsrv_fetch_array($stmt)){
echo $row['productID']. "<br/>";
}
$prev = $page - 1;
$next = $page + 1;
echo "<hr>";
//prev
if($prev > 0)
{
echo "<a href='?page=$prev'>prev</a> ";
}
//numbers
$number = 1;
for($number; $number <= $num_pages; $number +=1)
{
if($page==$number)
{
echo " <b>[$number]</b> ";
}
else
{
echo "<a href='?page=$number'>$number</a> ";
}
}
//next
echo "<a href='?page=$next'>next</a>";
I'm not familiar with sql server, but it seems to me you just need the end point:
$tsql = " SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY productID) AS
rownum, productID FROM products) AS products1
WHERE rownum >= $start AND rownum < ($start + $per_page)";
^ changed ^
And if $page is supposed to be an integer, it's always best to make sure that it is:
$page = (int) $_GET['page'];

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?
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
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.
Here is my code
which contains next and Previous button
<?php
$limit = 3; //set Number of entries to show in a page.
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else { $page=1;
}
//determine the sql LIMIT starting number for the results on the displaying page
$page_index = ($page-1) * $limit; // 0
$All_Users=mysqli_query($con,"select * from users limit $page_index, $limit");
while($row=mysqli_fetch_array($All_Users))
{
//show data in table or where you want..
}
$all_data=mysqli_query($con,"select count(*) from users");
$user_count = mysqli_fetch_row($all_data); // say total count 9
$total_records = $user_count[0]; //9
$total_pages = ceil($total_records / $limit); // 9/3= 3
if($page >= 2){
echo "<a href='blog.php?page=".($page-1)."' class='btn
customBtn2'>Previous</a>";
}
if($page<$total_pages) {
echo "<a href='blog.php?page=".($page+1)."' class='btn customBtn2'>NEXT</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

Categories