MySQL show results with inverted order? - php

I need to get the last 5 results, that's why I order them by Date DESC but I need to display the results from older to newer. How can I do this?
$data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 5");
while($row = mysql_fetch_array( $data ))
{
print "<img class='badge' title='" . $row['Site'] . "' src='http://getfavicon.appspot.com/http://" . $row['Site'] . "?defaulticon=1pxgif' />";
}

$results = array();
while($row = mysql_fetch_array($data)) {
$results[] = $row;
}
$results = array_reverse($results);
foreach ($results as $row) {
echo $row['Site']; // etc
}
Manual link: http://php.net/function.array-reverse.php

$data = mysql_query("
SELECT * FROM (
SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 5)
t ORDER BY Date
");
Also:
Please use mysql_real_escape_string (http://at2.php.net/manual/en/function.mysql-real-escape-string.php) for the variable $user. Depending on where you get that from it could be a security leak through sql injection.

You can actually order a second time in the same query.
I assume that you have an auto incrementad id (I'll call it 'EntryId' in this example) and then you hopefully should get what you need?
SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC, EntryId ASC LIMIT 5

Related

mySQL Order by Most Commented and Least Commented

I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";

Sort query by time and list next entries

I'm trying to sort this query by time.
I have a gaming match system. And I want to get a list of next 5 matches from my local time zone.
<?php
include_once "include/dbcompo.php";
$q=mysqli_query($con, "SELECT * FROM kamper ORDER BY tid LIMIT 5");
while($row = mysqli_fetch_array($q))
{
$clan1 = $row['clan1'];
$clan2 = $row['clan2'];
$server = $row['server'];
$tid = $row['tid'];
echo $clan1." ".$clan2." ".$server." ".$tid;
echo "<br />";
}
?>
Add a WHERE clause in your query: WHERE tid > NOW().
With NOW() you take the time of the server, maybe you should replace it with new DateTime(null)->getTimestamp()
Something like that:
<?php
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > NOW() ORDER BY tid LIMIT 5');
// or
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > '.new DateTime(null)->getTimestamp().' ORDER BY tid LIMIT 5');
?>
Two options:
1st option: Make the time field a numeric field and sort in PHP:
$queryResult = mysqli_query($con, $query);
while($row = mysqli_fetch_array($queryResult) {
$oldArray[$row['time'] = $row;
}
$array = ksort($oldArray);
foreach($array as $time=>$row) {
// do something
}
2nd option: Make a subquery
SELECT * FROM (
SELECT * FROM kamper WHERE timezone = 'UTC' ORDER BY tid
) LIMIT 5

Need help in displaying last 5 rows. PHP, MYSQL

Can anyone tell me what am I doing wrong. I would like to display the last 5 rows in desc order.
$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id desc limit 0,5")
or die(mysql_error());
while($row = mysql_fetch_array( $pull_activity_logs )) {
$activity_time = $row["datetime"];
$activity = $row["activity"];
}
echo "$activity";
Help would be deeply appreciated
Well, you can always select the first five in asc order, that would be last five in desc order, and then you could reverse their order in php if needed (5 values isnt anything what an array couldn't handle)
CODE:
$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id asc limit 5");
$temp_arr = array();
while($row = mysql_fetch_array( $pull_activity_logs )) {
$temp_arr[] = $row; //add to end
}
$final_arr = array_reverse($temp_arr);
foreach($final_arr as $row) //this doesn't have to be named $row
$activity_time = $row["datetime"];
$activity = $row["activity"];
echo "$activity";
}
EDIT:
now when i look at it maybe whole problem was in wring position of your echo:
$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id desc limit 0,5")
or die(mysql_error());
while($row = mysql_fetch_array( $pull_activity_logs )) {
$activity_time = $row["datetime"];
$activity = $row["activity"];
echo "$activity"; //this goes INSIDE the loop
}
You can retrieve the first five in ascending order and then order them in SQL by using a subquery:
select al.*
from (SELECT al.*
FROM activity_logs al
WHERE ac_no = '$logined_acc'
order by id asc
limit 0, 5
) al
order by id desc;

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

MySQL query within another query's while loop in PHP

I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.

Categories