PHP SELECT/Show last[number] items inserted in database - php

In my DB I have some "documents" which contain more items, I'm inserting that from my dashboard.
The thing is ; when displaying, the method requires a value in my case it's $id.
Right now I am using rand() with hardcoded range to show different "documents".
This is how it looks :
<?php
$num = rand(1,10);
$post->showSmallPost($num);
?>
Let's say i want to have three of these on HTML page. But instead of this rand() I want to show the last three ID imported to table. So that is my question, how to do it?
This is a method showSmallPost():
public function showSmallPost($id){
$connection = new Db();
$conn = $connection->connect();
$image = new Image();
$imgC = $image->showSmallImg($id);
$query = $conn->prepare("SELECT * FROM post WHERE id = ?");
$query->bind_param('i', $id);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
if ($row = $result->fetch_assoc()) {
$this->id = $row['id'];
$this->title = $row['title'];
$this->description = $row['description'];
echo "<div class=\"col-md-4 text-center\" style=\"margin-top: 5px;\">";
echo <<<EOT
<a href="news.php?post=$id">
$imgC
</a>
<h4 class="news-title">$this->title</h4>
<p class="news-para">$this->description</p>
EOT;
echo "</div>";
}
}
}
And yes, this showSmallImg() is just doing his job.

You can just add Sort to the Query.
You don't need to pass a random $id to the function.
You can change the SQL statement to:
$query = $conn->prepare("SELECT * FROM post ORDER BY id DESC LIMIT 0,1");
Also you can get 3 Documents in a Single Query With,
$query = $conn->prepare("SELECT * FROM post ORDER BY id DESC LIMIT 0,3");
You can even optimize the query to run faster,
$query = $conn->prepare("SELECT id, title, description FROM post ORDER BY id DESC LIMIT 0,3");
Also, rather than using HTML inside echo, you can create a multidimensional array of your preferred structure or use the one that the sql query returns.
And make use of foreach method and only print the Values inside the array with PHP and leave HTML as it is.
It will generate more cleaner code.
For Example:
<div class=col-md-4 text-center" style="margin-top: 5px;">
<?php echo $imgC; ?>
<h4 class="news-title"><?php echo $this->title; ?></h4>
<p class="news-para"><?php echo $this->description ?></p>
</div>

You can select the last id from the database, and create a for loop decrementing it.
$query = $conn->prepare("SELECT MAX(id) AS last_id FROM post");
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
$lastId = $row['last_id'];
for ($i = $lastId; $i > $lastId - 3; $i--)
{
$post->showSmallPost($i);
}
Alternatively, you can use the ORDER BY and LIMIT statements to get what you want.
$query = $conn->prepare("SELECT id FROM post ORDER BY id DESC LIMIT 3");
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
while ($row = $result->fetch_assoc())
{
$post->showSmallPost($row['id']);
}

If I'm understanding it right then you want to fetch the latest n records from a table and to do that you need to have a field like createdAt. Then you can write a query which will fetch the n records and order result by this createdAt field in descending order.
Your query then will look something like this
select * from posts order by createdAt desc limit 5;
This will give you the latest 5 records inserted into the table.

Related

Echo next row from MySQL

To select the previous row in MySQL I use the following script, which works perfect:
<?php
$previous = $row['id'] - 1;
$stmt = $db->query("SELECT * FROM data WHERE id = $previous");
while($row =$stmt->fetch()){echo ''.$row['title'].'';}
?>
In order to select the next row I want to use this script:
<?php
$next = $row['id'] + 1;
$stmt = $db->query("SELECT * FROM data WHERE id = $next");
while($row =$stmt->fetch()){echo ''.$row['title'].'';}
?>
This fetch the first record of the database and not the next row.
When you retrieve the previous row values, you write the data to $row, so when trying to fetch the next row, the value of $row['id'] is in fact the previous row id.
So store the value...
$currentID = $row['id'];
$previous = $currentID - 1;
// Other code
$next = $currentID + 1;
that is not the way you use mysql queries, you only want to run one query and then you loop on your results
either someting like
<?php
$stmt = $db->query("SELECT * FROM data ORDER BY id");
while($row =$stmt->fetch()){
echo ''.$row['title'].'';
}
?>
or
<?php
$stmt = $db->query("SELECT * FROM data ORDER BY id");
$results = $stmt->fetch_all(MYSQLI_ASSOC);
foreach ( $results as $key => $row ) {
echo ''.$row['title'].'';
}
?>
There is not need to add '1' in id and get the data. Its a bad idea. Accordingly if you want a next record then you should check a greater then, else use a lesser then for previous record. Simply...
$id=$row['id'];
next:
select * from <yout_table> where id = (select min(id) from <yout_table> where id > '$id')
previous:
select * from <yout_table> where id = (select max(id) from <yout_table> where id < '$id')
Its is work definitely....

How to echo result from query

Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.
$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);
echo $row;
I have it selecting the last row and supplying me with the stored data from the pageid of the last row.
I had to adapt my code. I believe it was because I use mysql. However, this code will work if you use mysqli
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
if ($resultpageid->num_rows > 0) {
while ($row = $resultpageid->fetch_assoc()) {
$pagenumber = $row["pageid"];
}
} else {
echo "0 results";
}
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.
Just fetch a single row and get the column from the returned array:
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();
if ($row) {
echo $row["pageid"];
} else {
echo "No record found!";
}

How can I store mysql results in different individual variables with one connection to the databse?

I am currently working on a personal project and I need your help.
After a lot of research I can't seem to find a proper solution to my problem(probably because I am not very good php developer - i am still learning).
Ok so I need to get 3 post titles from my database and store each one of them in individual variables. I need them to be individual because I want to use them in different parts of my website.
I have managed to do this but only by doing three different queries to the databse wich i suppose its bad. Is there a way to send one query to the databse and store them at once inside different variables?
I tried to do this with an array and although I was close enough I didn't seem to get this working.
Here is my code:
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 0,1');
$sslider_title1='';
while($row = $stmt->fetch()){
$sslider_title1 = $row['postTitle'];
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 1,2');
$sslider_title2='';
while($row = $stmt->fetch()){
$sslider_title2 = $row['postTitle'];
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 2,3');
$sslider_title3='';
while($row = $stmt->fetch()){
$sslider_title3 = $row['postTitle'];
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
So in order to get this running with one query i must do
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 0,3');
$sslider_title1='';
$sslider_title2='';
$sslider_title3='';
while($row = $stmt->fetch()){
\\ This is the part that I can't seem to solve :P
}
}
Please, do not use variables with such names.
What you need is array:
$titles = array();
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 0,3');
while($row = $stmt->fetch()){
$titles[] = $row['postTitle'];
}
}
Then in your code you can use
echo $titles[0];
echo $titles[1];
echo $titles[2];
for each of you titles.
If you don't want to store it in a variable this could be your answer:
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 0,3');
$sslider_title1='';
$row = $stmt->fetch()
$sslider_title1 = $row['postTitle'];
$sslider_title2='';
$row = $stmt->fetch()
$sslider_title3 = $row['postTitle'];
$sslider_title3='';
$row = $stmt->fetch()
$sslider_title3 = $row['postTitle'];
}
If you also don't know how many results you will get you may still use a loop:
try {
$stmt = $db->query('SELECT postTitle FROM blog_posts ORDER BY postID DESC limit 0,3');
for($i=0;$row = $stmt->fetch();$i++){
$sslider_title{$i}=$row['postTitle'];
}
}
But I really really recommend you use an array.

Display the latest 3 results from database

I need to display the latest 3 articles individually from the database (title, description, content and image).
$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 10";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($title_result))
{
$title = $row['title'];
$description = $row['description'];
$content = $row['content'];
$image = $row['image'];
}
echo $title;
Currently this only gets the latest one. How can I set variables for the second and third latest one? So I can have:
$title1
$title2
$title3
etc.
Thanks
the way you construct the code, it is supposed to echo out the 3rd item's tittle. so what you should do is go through loop and keep adding them to array like below:
and since you want latest 3 items, so wht not you limit it to only 3 items like below:
$title = array();
$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($title_result)) {
$title[] = $row['title'];
}
print_r($title);
The request what you have made to display the latest articles individually based on the id published into the DB. You need to modify the loop what you have provide over to the question.
If you want to display multiple products outside of any looping statement you have to make it store the values in an array() and after that you can use anywhere else outside the loop.
In order to make the variable as an array you can initialize an array() either in any of the two methods as you prefer.
Method: 1 - You can initialize the array() when the query returns the TRUE value.
Method: 2 - You can initialize the array() at the top of the page too.
Initializing is based on the convenience of the developer who is developing the code.
The basic Strategy for the MYSQL Limit Statement.
MySQL: SELECT LIMIT Statement
Description: The MySQL SELECT LIMIT statement is used to retrieve records from one or more tables in MySQL and limit the number of records returned based on a limit value.
Syntax:
The syntax for the SELECT LIMIT statement in MySQL is:
SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count
And hence you need to modify the query like follows so that you can display the latest three articles as per your requirement.
<?php
$title_query = "SELECT `title`, `description`, `content`, `image` FROM `articles` ORDER BY `id` DESC LIMIT 0,3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
$counting = $title_result->num_rows;
if($counting==0)
{
echo 'No Datas found';
}
else
{
// This part will execute if the count is greater than 0
$row=[];
while($fetch = $title_result->fetch_assoc()) {
$row[] = $fetch;
}
}
// here you can loop through to display the data.
foreach ($row as $key => $single_data) {
?>
Title: <?php echo $single_data['title']; ?>
Description: <?php echo $single_data['description']; ?>
Content: <?php echo $single_data['content']; ?>
Image: <img src="PATH to FOLDER WHERE YOU HAVE SAVED THE IMAGE ALONG WITH <?php echo $single_data['image']; ?>" />
<?php
}
?>

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

Categories