How to fetch mysql data in descending order? - php

So my application gets mysql data in json format and displays it in
id1 to id*
I have to update my database table every day and I want to show the recent data first, I don't want to change the entire table structure each and every time I update my database.
Is there any way that I can add rows in ascending order and fetch data in descending order so that my app will show the fresh data first?
Here is the encoder:
$connection = mysqli_connect("domain", "database user", "password", "database name");
$id = $_GET["id"];
$query = "SELECT * FROM my_data WHERE id BETWEEN ($id+1) AND ($id + 10)";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);

use order by desc like this
Select * from my_data where id between ($id+1) and ($id+10) order by id desc
Here your data shorted in descending order. and order follow in id. if you want to do order with any other field. than you can give name of field instead of id.

your code should be like this
<?php
$connection = mysqli_connect("domain","database user","password","database name");
$id = $_GET["id"];
$query = "Select * from my_data where id between ($id+1) and ($id+10) order by id desc";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
?>
Hope this will help you!!

Use below syntax
SELECT * FROM Table_Name order by Column_name DESC

for refference see this :
SQL Order By

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....

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

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.

How to select Single ID in MYSQL

I have a table citizens with a field id, title and link. If I use these codes it will display all the content of id, what I need is when I click the first id id it should display the content of the row. I tried to remove the loop and change the array to assoc but when I select the second id it will always display the 1 id.
mysql_select_db("do",$con1);
$sql = "SELECT * FROM citizens ORDER BY id DESC";
$myData = mysql_query($sql,$con1);
while($record = mysql_fetch_array($myData)){
echo $record['div'];
If you want to get single record from database with id=1, try following:
$myID = 1;
mysql_select_db("do",$con1);
$sql = "SELECT * FROM citizens WHERE id = $myID ORDER BY id DESC";
$myData = mysql_query($sql, $con1);
$record = mysql_fetch_row($myData);
echo $record['div'];

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.

Printing Duplicate Records In PHP / Mysql

I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}

Categories