In simple pagination, when clicking different no. 1,2,3,4, records from table not changing
as they should.
I'm displaying 5 records on each page,as on click 1 it display record from table 1 to 5,and so on.But,it is not changing.Help me.
<?php
mysql_connect("localhost","root","");
mysql_select_db("bluewater");
$page = $_GET["page"];
if($page=="" || $page=="1")
{
$page1=0;
}
else
{
$page1=($page*5)-5;
}
$sql=mysql_query("select * from countries limit 1,5");
while($ser = mysql_fetch_array($sql)) {
echo $ser["ccode"];
echo $ser["country"];
echo "<br>";
}
$sql=mysql_query("select * from countries");
$cou=mysql_num_rows($sql);
$a=$cou/5;
$a= ceil ($a);
echo "<br>"; echo "<br>";
for ($b=1;$b<=$a;$b++)
{
?><?php echo $b." ";?> <?php
}
?>
1) Don't use mysql_ functions, use mysqli_ or PDO.
2) To move via pages, you need to increase offset in query.
$page = $_GET['page'];
$itemsPerPage = 5;
$offset = ($page * $itemsPerPage) - $itemsPerPage;
$query = $db->prepare("SELECT * FROM `countries` LIMIT {$itemsPerPage} OFFSET {$offset}");
$query->execute();
$results = $query->fetchAll();
You never make use of your $page variable in the query. Change it to
select * from countries limit ".$page.", 5
and it should work
Also, mysql_real_escape_string($page)!
$sql=mysql_query("select * from countries limit $page1,5");
replace the first query with above code.
Just replace the your first sql query with the my sql query:
your sql query
$sql=mysql_query("select * from countries limit 1,5");
You provided static start limit is "1"
Correct Sql query:
$sql=mysql_query("select * from countries limit $page1,5");
Make its static limit is $page1 variable.
Try this approach.It is easier to understand.
//code for database connection
$left_rec=$rec_count-($page*$rec_limit);
$res=mysqli_query("select * from countries");
$rec_count=mysqli_num_rows($res);//Total no of records
if(isset($_GET['page']))
{
$page=$_GET['page']+1;
$offset=$rec_limit*$page;
}
else
{
$page=0;
$offset=0;
}
$rec_limit=5;//no of records per page
$offset=$page*$rec_limit;
$left_rec=$rec_count-($page*$rec_limit);
$res=mysqli_query("select * from countries limit $offset,$rec_limit");
while($row = mysqli_fetch_array($res))
{
echo $row["ccode"];
echo $row["country"];
echo "";
}
if($page==0)
{
echo"Next";
}
else if($left_rec <= $rec_limit)
{
$last=$page-2;
echo"Prev";
}
?>
Related
I've created different pages for 20 different rows in my php code, please have a look-
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = '';
}
if($page=='' || $page==1)
{
$page1=0;
}
else
{
$page1=($page*20)-20;
}
$query="SELECT * FROM issued_books limit $page1,20";
if($did_query_exec=mysqli_query($conn,$query))
{
while($query_exec=mysqli_fetch_array($did_query_exec, MYSQLI_ASSOC))
{
$isret = $query_exec["Date_returned"];
$dateret = $query_exec["Date_returned"];
$dateis = $query_exec['Date_issued'];
//echoing the values here
}
}
$query = "SELECT * FROM `issued_books`";
$Result = mysqli_query($conn, $query);
$cou = mysqli_num_rows($Result);
$a = $cou/20;
echo "</br></br>";
$a = ceil($a);
echo 'Page ';
for($b=$a; $b>=1; $b--)
{
echo "<a href='return-books.php?page=$b' style='text-decoration:none'>$b </a>";
}
The above code creates the link for all the pages with row 1 of page 1 contains the first record inserted by me.
I wish to display the recent most created record in row 1 of page 1
any kinda help would be really appreciated, thanks :)
You have to add ORDER BY with DESC:-
$query="SELECT * FROM `issued_books` ORDER BY id DESC limit $page1,20";
And
$query = "SELECT * FROM `issued_books` ORDER BY id DESC";
Note:- change the column name in ORDER BY according to your wish.
I have a php pagination script that I found online ( http://papermashup.com/easy-php-pagination/), and it works fine and i want to modify it to better suit my needs and update it a little bit. The problem i am having is that whilst it gives the number of results found, using
echo $total_pages.' Results';
It will not return a zero if there are no results it just simply has no value.
Here is the code that counts the number of results.
$query = "SELECT COUNT(*) as num FROM $tableName";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];
I have tried to add an if statement so that if the results are 0 i can say sorry no matches found, but i can not get the value to display if there are no results.
I have tried to echo COUNT as a row along with num but no matter what i do, i can not seem to get it to display 0 results.
Extending on your code:
$query = "SELECT COUNT(*) as num FROM {$tableName}";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages['num'];
if (!empty($total_pages)) {
echo $total_pages . " Results found.";
} else {
echo "Sorry! No results found.";
}
You can achieve this by using the function mysql_num_rows();
$result_set = mysql_query($query);
$count = mysql_num_rows($result_set);
p.s. please try to use mysqli rather than simple mysql as its deprecated now.
Try it.
$query = mysql_query("SELECT * FROM $tableName");
$num = mysql_num_rows($query);
if($num > 0)
{
echo "Total records = ".$num;
}
else
{
echo "Sorry no record found";
}
How to add pagination in this code?
I want to limited data in one page and I want in bottom as:
1 2 3 4 5 6 8 9 10
If I click on page 2 then my more results show on that page.
How can I do like that ?
<?php
//connect to database
mysql_connect('localhost','root','pasword');
mysql_select_db('root');
/* Get the letter user clicked on and assign it a variable called $sort */
$sort = $_REQUEST['letter'];
/* Let's check if variable $sort is empty. If it is we will create a query to display all customers alphabetically ordered by last name. */
if($sort == ""){
$qry= "SELECT * FROM tree ORDER BY keywords ASC " ;
}else{
/* if varible $sort is not empty we will create a query that sorts out the customers by their last name, and order the selected records ascendingly. */
$qry = "SELECT * FROM tree WHERE keywords LIKE '$sort%' ORDER BY keywords ASC" ;
}
/* Notice the use of '%' wilde card in the above query "LIKE '$sort%'". */
//next step is to execute the query.
$execute = mysql_query($qry) or die(mysql_error());
/* Before we display results let's create our alphabetical navigation. The easiest way to create the navigation is to use character codes and run them through the "for" loop. */
echo "<p>" ;
for ($i = 65; $i < 91; $i++) {
printf('%s | ',
$PHP_SELF, chr($i), chr($i));
}
echo "</p>" ;
/* now we are ready to display the results. Since out tbl_customers table has only three fileds we will display the results in a paragraphs. In the real world you may need to display the results in a table.
To display the results we will use "do while" loop to fetch the results. If no customers are found we will display an error message. */
if(mysql_num_rows($execute)>0){
do{
echo "<p>" .$result['id']. " " .$result['keywords']. " " .$result['meaning']. "</p>" ;
}while($result = mysql_fetch_assoc($execute));
}else{
echo "<p>No customer found.</p>" ;
}
?>
First select no of datas to generate page numbers by total_number of rows by no of pages per page
mysql_num_rows($execute);
use limit command to limit the data like this
$qry= "SELECT * FROM tree ORDER BY keywords ASC limit 0,10 " ;
then for every page number increment the limit index
You can use the below code
$page = $_GET['page'];
if ($page < 1)
{
$page = 1;
}
$conc=mysql_connect('localhost','root','');
mysql_select_db('employer',$conc);
$resultsPerPage = 5;
$startResults = ($page - 1) * $resultsPerPage;
$query = mysql_query('SELECT * FROM employee ') or die(mysql_error());
$numberOfRows=mysql_num_rows($query);
$totalPages = ceil($numberOfRows / $resultsPerPage);
$query = mysql_query("SELECT * FROM employee LIMIT $startResults,$resultsPerPage");
while ($output = mysql_fetch_assoc($query))
{
$result[]=$output;
}
for($i = 1; $i <= $totalPages; $i++)
{
if($i == $page)
echo '<strong>'.$i.'</strong> ';
else
echo ''.$i.' ';
}
$page = intval(abs($_GET['page'])); // get security ONE
if(mysql_num_rows($sql)) // get page number to empty location index.php
{
header('Location: index.php');
}
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on page 7 of 5 for instance.
I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an if statement to deal with this:
if ($page > $no_of_paginations) {
$page = $no_of_paginations;
}
However, I don't know where to place this. The reason being, $page needs to be defined before the mysql_query, but $no_of_paginations is defined after the query.
Any thoughts on how I can make this functional?
I'll post the pertinent code below:
<?php
$page = 0;
if(isset($_GET['page'])){
$page = (int) $_GET['page'];
}
$cur_page = $page;
$page -= 1;
if((int) $_GET['imgs'] > 0){
$per_page = (int) $_GET['imgs'];
} else {
$per_page = 16;
}
$start = $per_page * $page;
include"db.php";
$query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
echo "<ul class='new_arrivals_gallery'>";
while($row = mysql_fetch_assoc($result_pag_data)) {
echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
}
echo "</ul>";
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
?>
Thanks for your help!
As you are currently doing it, there would be no problem with moving the last section to above the main query.
A better way to find the total records with MySQL is to use the SQL_CALC_FOUND_ROWS keyword on your main query (so here it is SELECT SQL_CALC_FOUND_ROWS imgURL, imgTitle FROM images WHERE etc) then you can query SELECT FOUND_ROWS() and just get the number of records found in the last query. As well as being faster and more efficient, this avoids a race condition when records are added between the two queries.
However, in this case you should probably just do the two current queries in the reverse order as your only other option is to check at the end and repeat if necessary.
You should use query:
$query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
And instead of
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
use
$query_pag_num = "SELECT FOUND_ROWS()";
If you do the "SELECT COUNT(*) ..." query earlier in the script (at least before the other query), you will have $no_of_paginations earlier, and can use it to clamp $page to the correct range.
Sometimes you just have to bite the bullet and do a query twice. Accept the user-provided "I want page X" value, and try to get that particular page. If it ends up being past the end of the available data, you can either say "hey, wait... that ain't right" and abort, or redo the loop and default to the last available page.
while(true) {
$sql = "select sql_calc_found_rows .... limit $X,$Y";
$result = mysql_query($sql) or die(mysql_error());
$sql = "select found_rows();"; // retrieve the sql_calc_found_rows_value
$res2 = mysql_query($sql);
$row = mysql_fetch_array($res2);
$total_rows = $row[0];
if ($total_rows < $requested_row) {
... redo the loop and request last possible page ...
} else {
break;
}
}
details on found_rows() function here.
I am trying to create multiple pages from my query. If I have 100 results, and I want 10 results per page, I would like there to be ten pages created, with each page showing a different query. This is how my query is set up:
$sql ="SELECT * FROM Post WHERE (active ='1') ORDER BY PostID DESC ";
$result = mysql_query($sql,$db);
$numrows = mysql_num_rows($result);
while(($post = mysql_fetch_assoc($result))) {
$posts[] = $post;
}
<?php
if (!$numrows){ echo $errormessage;}
else{
foreach($posts as $post): ?>
echo stripslashes($post['text']);
<?php endforeach; }?>
This pulls each "post" from the database and puts displays them all out.
I would like to do something like this:
$results = mysql_num_rows($result);
$numpages = 10/$results; //gives the number of pages
while($numpages<$results)
{
//run code from above\\
}
What is the best way to do this with the method that I use? I appreciate your opinions because I'm at one of those stages where I'm lost in my own logic. Thank You!
Most pagination examples fail to meet real life requirements. A custom query string, for example.
So, here is a complete yet concise example:
<?
per_page=10;
// Let's put FROM and WHERE parts of the query into variable
$from_where="FROM Post WHERE active ='1'";
// and get total number of records
$sql = "SELECT count(*) ".$from_where;
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$total_rows = $row[0];
//let's get page number from the query string
if (isset($_GET['page'])) $CUR_PAGE = intval($_GET['page']); else $CUR_PAGE=1;
//and calculate $start variable for the LIMIT clause
$start = abs(($CUR_PAGE-1)*$per_page);
//Let's query database for the actual data
$sql = "SELECT * $from_where ORDER BY PostID DESC LIMIT $start,$per_page";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// and fill an array
while ($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
//now let's form new query string without page variable
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['page']);
if ($tmpget) {
$uri .= http_build_query($tmpget)."&";
}
//now we're getting total pages number and fill an array of links
$num_pages=ceil($total_rows/$per_page);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'page='.$i;
//and, finally, starting output in the template.
?>
Found rows: <b><?=$total_rows?></b><br><br>
<? foreach ($DATA as $i => $row): ?>
<?=$i?>. <?=$row['title']?><br>
<? endforeach ?>
<br>
Pages:
<? foreach ($PAGES as $i => $link): ?>
<? if ($i == $CUR_PAGE): ?>
<b><?=$i?></b>
<? else: ?>
<?=$i?>
<? endif ?>
<? endforeach ?>
It would be hideous to extract all data from the database and manage it from PHP. It would kill the RAM, and the network.
Use the LIMIT clause for paging.
First, you need to see the total number of records. Use
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1';
then,
$result = mysql_query($query, $db);
$row = mysql_fetch_assoc($result);
$count = $row['cnt'];
$pages = ceil($count/10.0); //used to display page links. It's the total number of pages.
$page = 3; //get it from somewhere else, it's the page number.
Then extract the data
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1 LIMIT '.$page*10.', 10';
$result = mysql_query($query, $db);
while($row = mysql_fetch_assoc($result))
{
//display your row
}
Then output the data.
I'm using that similar code to do that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
That code get total rows
and that for creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
You can also read about : pagination