pagination in php recent row first - php

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.

Related

My for loop only allows one post to be displayed, over and over again

/* 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

how do include multiple pieces of data on one page?

I cant figure out how to get multiple entries of data from my database. You can see below that I have newsID = 1, which allows me to get that to show on my database, but how should I change the code to be able to access other entries like newsID = 2 as well?
<?php
$queryAffinity = "SELECT * FROM affnews WHERE newsID = 1";
$stmt = $pdo->query($queryAffinity);
$row = $stmt->fetchObject();
?>
<?php if($row->newsID == 1) echo "<p>{$row->newsDescription}</p>"; ?>
this is the code im trying to use to echo the id 1
Edit your WHERE-Clause and put it in a loop. For example:
$queryAffinity = "SELECT * FROM affnews WHERE newsID = 1 OR newsID = 2";
$stmt = $pdo->query($queryAffinity);
while($row = $stmt->fetchObject())
{
//do something with $row
}
You Can use the following code:
$queryAffinity = "SELECT * FROM affnews WHERE newsID IN (1, 2)";
$stmt = $pdo->query($queryAffinity);
while($row = $stmt->fetchObject())
{
echo $row->id;
}

Pagination displaying issue php

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 articles on post 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("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

Creating multiple pages from sql query

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

Categories