Selecting the most popular entry from the last ten values entered - php

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

Related

I need to reverse the order of my ORDER BY results

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>";
}

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.

Get top 5 post count sql

I'm trying to get the top 5 users in my database according to their post count
<?php
$data = mysql_query("SELECT COUNT(*) FROM pins ORDER BY user_id ASC LIMIT 5")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "<table><tr><td>";
Print "".$info['user_id']."";
Print "</td></tr></table>";
}
?>
This is a code I have adapted which works for individual users with a WHERE user_id='999' clause. But how do I change it to get the top 5?
Use GROUP BY:
SELECT user_id
FROM pins
GROUP BY user_id
ORDER BY COUNT(*) DESC
LIMIT 5

Sorting SQL query with the submitting of a form

I have a general understanding of what I would like to do but not sure how to write the SQL.
Users have the ability from changing the sort from ASC to DESC and increase the query limit from 5 to 10.
$result=$mysqli->query("SELECT * FROM table WHERE status = 3 ORDER BY name ASC LIMIT $start_from, 5");
the option box for asc/desc will end up being $sort_order
the option box for limit will be $limita
I tried to write it like
$result = "SELECT * FROM wp_pod_tbl_bars WHERE status = 3";
if(!empty($limita)){$result.="LIMIT $limita, 5";}
if ($result = $mysqli->query($result)) {
while($row = $result->fetch_object()){
but the query ended up empty due to the query being split into different lines.
Any idea what I am doing wrong? ill post more code if needed but this is generally where my issue is.
Put space between status and LIMIT.
$result = "SELECT * FROM wp_pod_tbl_bars WHERE status = 3";
if(!empty($limita)){$result.=" LIMIT '".$limita."', 5";}
---------------^

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

Categories