I need to reverse the order of my ORDER BY results - php

I need to get 3 rows with the lowest value in a certain column, and then reverse the order of these 3 rows. So if the 3 rows with the lowest value are A, B and C, I need to sort them as C, B and A. Could I do that in a single SQL statement?
$sql = "SELECT * FROM ratings_table ORDER BY rating DESC LIMIT 3";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<td>".$row['rating']."</td>";
}
}
With this code I will get the right results but in the wrong order.

You'll want to use a subquery, like this:
SELECT *
FROM
(
SELECT *
FROM ratings_table
ORDER BY rating ASC LIMIT 3
) a
ORDER BY rating DESC
This will take the lowest three results , then flop the order.

Only a sub-query will work. First you select the 3 lowest values and then sort them.
Something like:
SELECT * FROM (
SELECT <COLUMN_VALUE>
FROM <YOUR_TABLE>
ORDER BY <COLUMN_VALUE> LIMIT 3
) T
ORDER BY <COLUMN_VALUE> DESC

$sql = "SELECT * FROM ratings_table ORDER BY rating DESC LIMIT 3";
$result = mysqli_query($conn, $sql)->fetch_all();
krsort($result)
foreach ($result as $row)
{
echo "<td>".$row['rating']."</td>";
}

Related

How to count contents of last n rows mysql

I am trying to figure out how to see how many times in the past 7 entries/rows that sleep = 1.
Currently, $num shows the number of times sleep = 1 in all rows. I have seen that 'order by xxx desc limit 7' has been suggested in other answers but it doesn't seem to work well in this scenario. Would greatly appreciate any help, thanks!
Heres my code:
$result = mysqli_query($conn, "SELECT count(*) FROM test_table WHERE sleep = 1");
$row = mysqli_fetch_row($result);
$num = $row[0];
You can try this one:
SELECT a, COUNT(b) FROM test_table
WHERE sleep = 1
GROUP BY a
ORDER BY COUNT(b) ASC
LIMIT 7
Here, a is the name of your column you are trying to count
And, b is any column name for usage to count (it can id, or any column name)
If the sleep is binary/tinyint you can just sum that in the query with the order by.
SELECT sum(sleep)
FROM table
ORDER BY COUNT(id) DESC
LIMIT 7
If sleep isn't binary you can use a case statement.
SELECT sum(case when sleep = 1 then 1 else 0 end) as totalsleep
FROM table
ORDER BY COUNT(id) DESC
LIMIT 7
Here's my idea, get all the data in test_table and create a loop that will count the sleep, like this
$result = mysqli_query($link, "SELECT sleep FROM test_table;");
$x=1;
$sleep = [];
$SleepCount= 0;
while($row = mysqli_fetch_array($result)) {
if($row[0] == "1"){
$SleepCount++;
}
if($x == 7){
array_push($sleep,$SleepCount);
$SleepCount = 0;
$x=0;
}
$x++;
}
echo "<pre>",print_r($sleep),"</pre>";

MySQL 1 Table, 1 Select, Multiple Wheres

I am trying to add a "Related Products" section below my product. I can only get this to work if
I use two separate SELECTS. I am trying to combine them but can't get it to work.
Same Table in MySQL -
<?php
//select items from db
$items = mysql_query
("SELECT * FROM table WHERE (myinvno='dg300')
OR (action='alive' AND cate='dogs'
ORDER BY productNo ASC LIMIT 0, 4)");
or die(mysql_error());
while($item = mysql_fetch_array($items))
{
?>
This part is for the Related Products section:
OR (action='alive' AND cate='dogs'
ORDER BY productNo ASC LIMIT 0, 4)");
Thank you ~
The correct syntax would look like:
$items = mysql_query("
SELECT *
FROM table
WHERE (myinvno = 'dg300') OR
(action = 'alive' AND cate = 'dogs')
ORDER BY productNo ASC
LIMIT 0, 4"
);
You were missing a closing parent after 'dogs'.
EDIT:
Hmmm . . . I wonder if this is what you want:
SELECT *
FROM table
WHERE (myinvno = 'dg300')
UNION ALL
(SELECT *
FROM table
WHERE (myinvno <> 'dg300') AND
(action = 'alive' AND cate = 'dogs')
ORDER BY productNo ASC
LIMIT 0, 4
);
This gets all rows that match the first condition plus four more that match the second.

Creating a subquery with mysqli in PHP to fetch array last 10 results in ascending order

I thought this would be simple but I'm having a tough time figuring out why this won't populate the the data array.
This simple query works fine:
$queryPrice = "SELECT price FROM price_chart ORDER BY id ASC LIMIT 50";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
But instead I want it to choose the last 10 results in Ascending order. I found on other SO questions to use a subquery but every example I try gives no output and no error ??
Tried the below, DOESN'T WORK:
$queryPrice = "SELECT * FROM (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
I also tried specifying the table name again and using the IN, also doesn't work:
$queryPrice = "SELECT price FROM price_chart IN (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
In both examples my array is blank instead of returning the last 10 results and there are no errors, so I must be doing the subquery wrong and it is returning 0 rows.
The subquery doesn't select the id column, so you can't order by it in the outer query. Also, MySQL requires that you assign an alias when you use a subquery in a FROM or JOIN clause.
$queryPrice = "SELECT *
FROM (SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) x ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice) or die (mysqli_error($conn));
$data = array();
while ($row = mysqli_fetch_assoc($resultPrice)) {
$data[] = $row['price'];
}
You would have been notified of these errors if you called mysqli_error() when the query fails.
Your second query is the closest. However you need a table alias. (You would have seen this if you were kicking out errors in your sql. Note you will need to add any field that you wish to order by in your subquery. In this case it is id.
Try this:
SELECT * FROM (SELECT price, id
FROM price_chart ORDER BY id DESC LIMIT 10) as prices
ORDER BY id ASC
You must have errors, because your SQL queries are in fact incorrect.
First, how to tell you have errors:
$resultPrice = mysqli_query (whatever);
if ( !$resultprice ) echo mysqli_error($conn);
Second: subqueries in MySQL need aliases. So you need this:
SELECT * FROM (
SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) AS a
ORDER BY id ASC";
See the ) AS a? That's the table alias.

MYSQL - Get Next and Previous Record by ID - HTML for hyperlinks

So I'm trying to add a little bit of convenience to a CRUD by adding next and previous links to navigate between records in my database.
Here are my queries:
$id=$_GET['id'];
$id = $currentid;
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery);
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
?>
Here is my HTML:
Previous
Next
Now I tested these queries in PHPMyAdmin and they produced the result I wanted, but I can't get my hyperlinks to actually be supplied with the correct IDs... they're just blank after the =. What am I doing wrong?
mysql_query() returns a result set (resource). To get the actual rows from the result set, you need to use a function like mysql_fetch_row().
Your code for the "next" link would look something like:
PHP
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
if(mysql_num_rows($nextresult) > 0)
{
$nextrow = mysql_fetch_row($nextresult);
$nextid = $nextrow['id'];
}
HTML
Next
and the previous link would be done similarly.
Obligatory note: For new code, you should seriously consider using PDO.
Advanced note:
You could combine your queries into a single query like:
SELECT
(
SELECT id
FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1
) AS previd,
(
SELECT id
FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1
) AS nextid
And then adjust the logic accordingly.
Okay, It took a little bit but I figured it out...
PHP
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery) or die(mysql_error());
while($prevrow = mysql_fetch_array($prevresult))
{
$previd = $prevrow['id'];
}
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery) or die(mysql_error());
while($nextrow = mysql_fetch_array($nextresult))
{
$nextid = $nextrow['id'];
}
HTML
Previous
Next
Thanks for the help, I think it put me on the right course. I'll look into that PDO stuff for the future. I'm just now starting to get a hang of the old MYSQL/PHP syntax and now all the sudden there's a new format... tough to keep up with it all!
The resultant code has a culprit at the very beginning and end of the table. Your code will "die" as you ordered. Instead you might check the query results ($prevresult, $nextresult) and decide NOT to show a link for previous or next item.
SELECT
IFNULL(
(SELECT id FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1 ) , (SELECT id FROM inventory ORDER BY id DESC LIMIT 1 )
) AS previd ,
IFNULL(
(SELECT id FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1 ),
(SELECT id FROM inventory ORDER BY id ASC LIMIT 1 )
) AS nextid

Selecting the most popular entry from the last ten values entered

I have the selecting from the last ten entries working, but am unsure how to get the most popular from these ten entries? Also how would I count the number of the most popular entry & output it to a percentage?
<?php
$sql = "SELECT data FROM table_answers ORDER BY id DESC LIMIT 10";
$result = mysql_query ($sql, $db);
while ($row = mysql_fetch_array ($result))
{
echo "[".$row['data']."]";
}
?>
And I have tried to do the WHERE value as well but it doesn't return any result.
$sql = "SELECT data FROM table_answers WHERE id IN (SELECT id FROM table_answers
ORDER BY id DESC LIMIT 10) ORDER BY popularity DESC LIMIT 1";
$result = mysql_query ($sql, $db);
while ($row = mysql_fetch_array ($result))
{
echo " [".$row['data']."] ";
}
Anyone have any idea what I might be doing wrong here? please
This should solve the problem -
SELECT tableorder.*
FROM (SELECT *
FROM table
ORDER BY id DESC
LIMIT 10) tableorder
ORDER BY tableorder.popularity DESC
LIMIT 1
The inner query will sort on the basis on id and get the top 10. The outer will again sort the 10 rows on the basis of popularity and return the row with highest popularity.
SELECT data
FROM (
SELECT data
FROM table_answers
ORDER BY id DESC
LIMIT 10
) t
ORDER BY popularity

Categories