How to count contents of last n rows mysql - php

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

Related

MYSQL query greater than AND lesser than

I have a table named character_level:
level experience
1 0
2 998
3 2994
4 5988
and so on.
I have another table user_Character¨
ID character_current_xp
1 150
2 35
to check if level must be changed I do this:
$xp = mysqli_query($con,"SELECT character_current_xp FROM user_character WHERE ID = '$currentUser'");
while($row = mysqli_fetch_array($xp))
{
$current_xp = $row['character_current_xp'];
}
$lvl2 = mysqli_query($con,"SELECT level FROM character_level WHERE experience <= $current_xp order by experience desc limit 1");
while($row = mysqli_fetch_array($lvl2))
{
$level_after = $row['level'];
}
if(isset($_POST['accept_xp'])){ //with this i check ressults
$setxp = "UPDATE user_character SET character_current_xp = character_current_xp+100, character_current_lvl = $level_after WHERE ID = $currentUser";
mysqli_query($con, $setxp);
mysqli_close($con);
header('Location: account.php');
}
Problem is wheither i use <= $current_xp order by experience desc limit 1 weither >= $current_xp order by experience desc im still off by one level.
Anyone can shoot me anything?
Thanks in advance.
Chris
Well, here's something:
SELECT l.level
FROM user_character c
JOIN character_level l
ON l.experience <= c.character_current_xp
WHERE ID = '$currentUser'
ORDER
BY experience DESC
LIMIT 1

Count the number of values that are bigger than 20

I have a table in my database, tbl. In that table I have id and num, both as regular int values.
I want to count how many IDs have num that is bigger than 20 (num > 20). Just to count how many rows have num > 20. I wrote this:
$counter= 0;
$sqlQuery = "select num from tbl";
$finalResult= $databasename->prepare($sqlQuery );
$finalResult->execute();
$numArr= $finalResult->fetchColumn();
foreach ($numArra $row){
if($row > 20)
$counter++;
}
echo ($counter);
The problem is, that it prints 0 everytime... Thanks in advance.
You don't need any of this. Just do
SELECT COUNT(*) FROM tbl WHERE num > 20
If you want to plug that into PHP and if you want to do this dynamically.
$finalResult= $databasename->prepare("SELECT COUNT(*) FROM tbl WHERE num > ?");
$finalResult->bindParam(1,$someParam);
$finalResult->execute();
$numArr = $finalResult->fetchColumn();
echo ($numArr);
Much simpler

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.

Display number of duplicates from database [SQL]

This is my code.
$sqlcount = "SELECT count(*) AS C, Horse_ID FROM images WHERE Horse_ID = 24 GROUP BY Horse_ID HAVING COUNT(*) > 1 LIMIT 0, 30";
//echo $sqlcount;
$resultcount = $conn->query($sqlcount);
$rowcount = $result->fetch_assoc();
echo $rowcount['C'];
Why won't it echo the number 4, which is what shows when I test it in phpmyadmin? There are 4 duplicate values in that table hence the 4.
$rowcount = $result->fetch_assoc();
to
$rowcount = $resultcount->fetch_assoc();
If you want the number of duplicates in the database, why not write the query to get that value?
SELECT COUNT(*)
FROM (SELECT count(*) AS C, Horse_ID
FROM images
WHERE Horse_ID = 24
GROUP BY Horse_ID
HAVING COUNT(*) > 1
) i;
Then, you will only be returning one value from the database to the application (which is faster) and there is no need to artificially limit the count to 30.

PHP MySQL select random rows

I have a problem selecting 6 random friends
This is the query I've got so far:
$result = num_rows("SELECT * FROM friends WHERE member_id = '".$_SESSION['userid']."'");
if($result >= 6) {
$f_num = 6;
} else {
$f_num = $result;
}
for($i = 1; $i <= $f_num; $i++) {
$q_get_member_friends = mysql_query("SELECT * FROM friends WHERE member_id = '".$_SESSION['userid']."' ORDER BY rand() LIMIT 1");
$r_get_member_friends = mysql_fetch_array($q_get_member_friends);
echo $r_get_member_friends['friend_with'];
}
I want to select 6 random friends if the logged in user has more or equal to 6 friends
Stuck on this for a while now :/
Thanks for any help :)
If you use:
SELECT *
FROM friends
WHERE member_id = '".$_SESSION['userid']."'
ORDER BY rand()
LIMIT 6
If the person only has 3 friends, the query will only show those three - it doesn't mean that the query will always return six rows.
The best way I've found to select any number of random records is with OFFSET in the query.
Let's say you want 6 random records, so I'll borrow from an answer above and count the total number of friends in the database.
$sql = mysql_query("SELECT COUNT(*) AS total FROM friends WHERE member_id='". $_SESSION['userid'] ."'");
$get_count = mysql_fetch_array($sql); // Fetch the results
$numfriends = $get_count['total']; // We've gotten the total number
Now we'll get the 6 random records out of the total above (hopefully it's > 6),
$query = mysql_query("SELECT * FROM friends WHERE member_id='". $_SESSION['userid'] ."' LIMIT 6 OFFSET " . (rand(0, $numFriends));
while ($rows = mysql_fetch_array($query))
{
/// show your $rows here
}
Using OFFSET may not be the best or most efficient, but it's worked for me on large databases without bogging them down.
Never mind, I figured it out :)
Had to use while not for :'D
First select the number of friends that the user has:
"SELECT COUNT(*) as numFriends FROM friends WHERE member_id='".$_SESSION['userid']."'
...put that into a variable, let's call it "$numFriends"
Then:
for($z=0;$z<6;$z++)
{
$randomFriendIndex = rand(1,$numFriends);
//Get the friend at that index
}
change limit 1 to limit 6 on the eighth line.
Instead of SELECT * at the beginning, try SELECT COUNT(*) and use the actual return value instead of num_rows().
Your loop could generate duplicates. I would suggest trying OMG Ponies answer.
There is a whole chapter about random selection in the book SQL Antipatterns.

Categories