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
Related
/* To sort the id and limit the post by 40 */
$sql = "SELECT * FROM requests";
$result = $conn->query($sql);
$sqlall= "SELECT * FROM requests ";
$resultall = $conn->query($sqlall);
$i = 0;
if ($result->num_rows > 0) {
// Output data of each row
$idarray= array();
while($row = $result->fetch_assoc()) {
echo "<br>";
// Create an array to store the
// id of the blogs
array_push($idarray,$row['id']);
}
}
else {
echo "0 results";
}
?>
<?php
for($x = 1; $x < 40; $x++) {
// This is the loop to display all the stored blog posts
if(isset($x)) {
$query = mysqli_query(
$conn,"SELECT * FROM `requests`");
$res = mysqli_fetch_array($query);
$email1 = $res['email1'];
$msg1= $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
the output is 40 cards reading data from the first row in my database. can anyone help?
I'm using xampp.
This code is to show the loop, but if anyone wants the full code is here
You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests` 40 more times, and always extract the same first row. You never use the ID to change the query.
But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:
$sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
$result = $conn->query($sql);
while ($res = $result->fetch_assoc()) {
$email1 = $res['email1'];
$msg1 = $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
//example output, just for demo:
echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
}
Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html
I want to make select and print out all of the tables I have (I got that so far), and then limit it using `` and then ordering them by table name, and have 10 results per page.
How would I go about doing that? I know how to do it getting data from tables, but I don't know how to do it using just tables.
I have this so far:
function list_tables($type){
$sql = "SHOW TABLES FROM example";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_name = $row[0];
echo $table_name; //edited out a lot to keep it simple
//I'm just printing out a lot of data based on table name anyway
}
mysql_free_result($result);
}
So far, it only prints out all of the table names (+ extra info I print for table names) all in the same page and it's getting the the point where it takes forever to scroll. I'd like to limit it to about 10-20 posts per page instead of a few hundred posts on one page.
Thanks in advanced if anyone can help me. Much appreciated.
Calculate the offset and limit according to the page number and try the below query:
function list_tables($type, $offset, $limit){
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'example' ORDER BY TABLE_NAME LIMIT $offset, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_name = $row[0];
echo $table_name; //edited out a lot to keep it simple
//I'm just printing out a lot of data based on table name anyway
}
mysql_free_result($result);
}
Use below given query which supports LIMIT so you can do pagination with your table names.
select * from information_schema.tables LIMIT 5
i did this:
function list_tables(){
$amtperpage = 15;
$sql = "SELECT COUNT(TABLE_NAME) FROM information_schema.tables WHERE TABLE_SCHEMA = 'my_dbname'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total_rows = $row[0];
//pagination stuff here
if(isset($_GET['p'])) $curpage = intval($_GET['p']); else $curpage=1;
$start = abs(($curpage-1)*amtperpage);
$sql = "SELECT TABLE_NAME FROM information_schema.tables ORDER BY TABLE_NAME ASC LIMIT $start,$per_page";
$res = mysql_query($sql);
while($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['p']);
if($tempget){
$uri .= http_build_query($tmpget)."&";
}
$num_pages=ceil($total_rows/$amtperpage);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'p='.$i;
?><div id="container">Pages:
foreach ($PAGES as $i => $link){
if($i == $curpage){
=$i
} else {
?><?=$i?>
}
} ?>
foreach($DATA as $i => $row){
$table_name = $row[0];
//use my functions to get data for each table name and list it and such
}
}
this is highly butchered since I have a lot of stuff that would've gotten in the way of the point but this should work. Thanks to the people who helped me. :)
<?php
mysql_select_db($database_XXX, $XXX);
$result= mysql_query("SELECT COUNT(*) FROM news");
$total = mysql_result($result, 0, 0);
// create a random number
mt_srand((double)microtime()*1000000);
$number = mt_rand()%$total;
// get a random entry
$result= mysql_query("SELECT * FROM news LIMIT $number, 5");
$row = mysql_fetch_array($result);
?>
This is the PHP code I'm using and it pulls up random data from the table I want but I can't seem to figure out how to have it not show the current post it's on. Will I need to throw in an if statement in? If I do where would it go and how to impletment it. The only thing I can thing of is using if statements to check if the post_id on page matches the post_id posted. But I'm new to this and the only thing I can think of is.
if(!$row['post_id'] == $_GET['id']) {
}
I don't know what to make it do after. Also if anyone knows how or can help point me in the right direction that would be great. Thanks.
Here is the update of the total thing here. It still shows post it's already on. hope this helps. This is the php code for the page.
<?php
mysql_select_db($database_xxx, $xxx);
$result= mysql_query("SELECT COUNT(*) FROM news");
$total = mysql_result($result, 0, 0);
// create a random number
mt_srand((double)microtime()*1000000);
$number = mt_rand()%$total;
// get a random entry
$result= mysql_query(sprintf("SELECT * FROM news WHERE post_id <> %d LIMIT %d, 3", $post->post_id, $number));
$row = mysql_fetch_array($result);
?>
<?php
if (! isset($_GET['id']) || (int) $_GET['id'] === 0 ) {
echo "Incorrect input, aborting";
exit;
}
mysql_select_db($database_xxx, $xxx);
$sql = "SELECT * FROM news WHERE post_id = " . $_GET['id'];
// a line of debug to make sure things are as expected
$query = MYSQL_QUERY($sql);
// query your table for a match with post_id
if (mysql_num_rows($query) == "1")
// if a record is found, show the info
{
$fetch = mysql_fetch_array($query); // set $fetch to have the values from the table
} else {
echo "No match in database found."; // if no match is found, display this error
}
?>
Assuming that code is on the page where you view the main product:
$result= mysql_query(sprintf("SELECT * FROM news WHERE id <> %d LIMIT %d, 5", $post->id, $number));
Also, you should not be using mysql_* functions anymore as they are deprecated; checkout PDO
I am working on a site which displays products from a database in a listed format, so far so good. However, I would like to add a simple checkbox above which, when ticked, orders the list by price, lowest to highest (and also another one from highest to lowest). I have tried to do this but I'm having problems.
First I added a checkbox (see HTML below) labelled "order by lowest price". Then I added a line to my php code just below the main database query (about 10 lines down my PHP code), which tries to append a piece of query language on the end of the database query, which is just above, however it doesn't seem to work.
I just want to make it so that when the user checks the checkbox, it is sorted by cheapest to most expensive. What have I done wrong?
Note: 'buynow' is where the price data is stored for each row.
HTML
<form action="spain-holidays.php" method="post">
<p>Order by lowest price:</p><input name="orderbyprice" type="checkbox" value="orderbyprice" />
</form>
PHP
<?php
//connect
include ("db.connect.php");
//pagination
$per_page = 20;
$pages_query = mysql_query("SELECT COUNT('id') FROM `holidaytable` WHERE brandname = 'Spain'");
$count = mysql_result($pages_query, 0);
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
echo '<p>There are '.$count.' holidays<hr></p><br /><br />';
//construct query and insert values
$query = mysql_query("SELECT * FROM holidaytable WHERE brandname = 'Spain' LIMIT $start, $per_page") or die(mysql_error());
//THIS IS THE LINE I ADDED HERE:
if (isset($_POST['orderbyprice'])) $query .= " ORDER BY buynow ASC";
while($rows = mysql_fetch_assoc($query)) {
$name = $rows['name'];
$id2 = $rows['id2'];
$hotelname = $rows['hotelname'];
$desc = $rows['desc'];
$spec = $rows['spec'];
$resort = $rows['resort'];
$awtrack = $rows['awtrack'];
$awthumb = $rows['awthumb'];
$awimage = $rows['awimage'];
$mthumb = $rows['mThumb'];
$mlink = $rows['mlink'];
$mimage = $rows['mimage'];
$buynow = $rows['buynow'];
$awcatid = $rows['awcatid'];
$mcat = $rows['mcat'];
$brandname = $rows['brandname'];
echo "<div class='resultbox'>
<div class='resultboxtopbar'>
<div class='hotelname'><h3>$hotelname</h3></div>
<div class='price'><h3>From <strong>£$buynow</strong> $spec</h3></div>
</div>
<div class='resultboxmain'>
<div class='resultboximage'><a href='$awtrack' target='_blank'><img src='$mimage' /></a></div>
<h4>$resort, $brandname</h4>
<p>$name</p>
<p>$desc...</p>
<div class='moreinfobutton'><input name='moreinfo' type='button' value='moreinfo' /></div>
</div>";
//more pagination, etc
mysql_query() does not return a string and therefore cannot be appended to. You should do something like this instead:
$sql = "SELECT * FROM holidaytable WHERE brandname = 'Spain' LIMIT $start, $per_page";
if (isset($_POST['orderbyprice'])) $sql .= " ORDER BY buynow ASC";
$query = mysql_query($sql) or die(mysql_error());
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.