Count the number of values that are bigger than 20 - php

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

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

How to count number from highest to lowest number column in sql and php?

Example column in sql:
id|viewed
1|1000
35|500
47|1200
79|700
84|300
I use "SELECT * FROM table ORDER BY viewed desc", the result I get:
47|1200
1|1000
79|700
35|500
84|300
But I want to add "number order" by Top id ( like ranking ) in PHP, example text:
ID 47 is 1
ID 1 is 2
ID 79 is 3
ID 35 is 4
ID 84 is 5
So what I need to add these top with PHP guys, I think will use $i++ to count number or something like this in php ?
Increment a variable during the loop that prints the results.
$i = 1;
while ($row = $stmt->fetch()) {
echo "ID {$row['id']} is $i<br>";
$i++;
}
You can do it from the sql query itself :
May be you should try this:
set #row_num = 0;
SELECT #row_num := #row_num + 1 AS number,id,viewed FROM `table` ORDER BY viewed desc
Something like this?
$query = $db->query("SELECT * FROM table ORDER BY viewed desc");
$rows = $query->fetchAll(PDO:FETCH_ASSOC);
count = count($rows);
echo '<ul>';
for ($x = 0; $x < count; $x++) {
echo '<li>ID ' + $rows[$x]['id'] + ' is ' + $x + '.</li>'
}
echo '</ul>';

PhP/MySQL: how to dynamically change my (large and always changing) database

Scenario
I have a MySQL database with 10.000 rows. Setup of the database:
ID UniqueKey Name Url Score ItemValue
1 5Zvr3 Google google.com 13 X
2 46cfG Radio radio.com -20 X
3 2fg64 Yahoo yahoo.com 5 X
.... etc etc etc
As you can see, each item has a score. The score is constantly changing. Google may have a score of 13 now, but tomorrow it may be 80, or -50.
What I want:
I want to create a system that creates a hierarchy in my current database, based on the score of the items. Right now I'm thinking about percentile ranks, meaning that the highest scoring items will be close to 100%, and the lowest scoring items will be close to 0%. For this I created some code that will try to achieve what is shown here: http://www.psychstat.missouristate.edu/introbook/sbk14m.htm
This is my code:
$sql = "SELECT * FROM database order by Score";
$result = $conn->query($sql);
$count = 0;
while ($row = $result->fetch_assoc()) {
$woow = $row['Score'];
$sql = "SELECT * FROM database WHERE Score = $woow";
$resultnew = $conn->query($sql);
$somanythesame = $resultnew->num_rows;
$itemPercentile = ( ($count/$result->num_rows + 0.5*$somanythesame/$result->num_rows) * 100 );
$rowID = $row['ID'];
$sql2 = "UPDATE database SET itemValue = $itemPercentile WHERE ID = $rowID";
$conn->query($sql2);
$count++;
}
This works, but for one problem it does not: There are many items in my database, many with the same score. To illustrate my problem, here is a very simple 10-row database with only the Scores:
Scores
-10
0
0
0
10
20
20
30
40
50
The problem with my code is that it doesn't give the same percentile for the items with the same Score, because it takes in account all previous rows for the calculation, including the ones with the same Score.
So, for the 2nd, 3rd and 4th item with a Score of 0, it should be like this: (1/10 + 0.5*1/10) * 100. Problem is, that for the 3rd item it will do (2/10 + 0.5*1/10) * 100 and the 4th item it will do (3/10 + 0.5*1/10) * 100.
Then, for the 5th item with a score of 10, it should do (4/10 + 0.5*1/10) * 100. This is going well; only not for the items with te same score.
I'm not sure if I explained this well, I find it hard to put my problem in the right words. If you have any questions, let me know! Thank you for your time :)
You need to maintain an "identical count" ($icount) variable that tracks the number of items with an identical score and a "current score" ($score) that tracks the current score.
$icount = 0;
$score = null;
Increment $icount instead of $count when $woow == $score (identical value check). Otherwise, add it to your $count and increment, and then reset the $icount value to 0.
if ($woow == $score) {
$icount++;
} else {
$count += $icount + 1;
$icount = 0;
}
Finally, set your $score value to the latest $woow for testing in the next iteration of the loop:
$score = $woow;
This will allow items with the same Score to have the same $count value, while incrementing an additional $icount times when a new $score is found.
Your final code will look like this:
$sql = "SELECT * FROM database order by Score";
$result = $conn->query($sql);
$count = 0;
$icount = 0;
$score = null;
while ($row = $result->fetch_assoc()) {
$woow = $row['Score'];
$sql = "SELECT * FROM database WHERE Score = $woow";
$resultnew = $conn->query($sql);
$somanythesame = $resultnew->num_rows;
$itemPercentile = ( ($count/$result->num_rows + 0.5*$somanythesame/$result->num_rows) * 100 );
$rowID = $row['ID'];
$sql2 = "UPDATE database SET itemValue = $itemPercentile WHERE ID = $rowID";
$conn->query($sql2);
if ($woow == $score) {
$icount++;
} else {
$count += $icount + 1;
$icount = 0;
}
$score = $woow;
}
You can change $sql query:
$sql = "SELECT *,count(*) FROM database group by Score order by Score";
In this case, you fetch score with counts and no more select needed in the while loop.
Even you can select Percentile in MySQL query:
Select t2.* , #fb as N , ((t2.fb1 + 0.5 * t2.fw)/#fb*100) as percentile from (
Select t1.* , (#fb := #fb + t1.fw) as fb1 from (
Select score,count(*) as fw From tablename group by score order by score ASC
) as t1
) as t2
I think this query returns most of columns which you may needs to check results.

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 limit range numbers

I would like get number of records in a table then divide them by 4, after dividing them by 4 i want to create sql statements with limit ranges based on my result. For example I have a table with 8 records I divide by 4, I will create 2 sql statements with a limit range like limit 0,4 and limit 4,8
Final results will look like
Select * from prop where id=123 LIMIT 0,4
Select * from prop where id=123 LIMIT 4,8
My approach was to have for loop which will count the number of sql statements to be made.
Then in the loop: first circle 0-4 and second will be 4-8
Am struggling on the limit 0-4 and limit 4-8
PHP script
include('connect.php');
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$results_query_1 = mysql_query($query_1);
while($row_query_1 = mysql_fetch_array($results_query_1))
{
$cnt = $row_query_1['Total'];
}
echo $cnt;
echo "<br>";
$num_grps = 0;
if ($cnt % 4 == 0 )
{
echo $num_grps = $cnt / 4 ;
}
$count_chk= $num_grps * 4;
for ($i=1;$i<=$num_grps;$i++)
{
//for loop for range
for()
{
$range = '0,4';
echo "SELECT prop_ref from prop limit".$range;
}
}
Either you've not understood the problem or haven't explained it very well.
The most immediate problem here is that you have misunderstood the syntax for the LIMIT clause. The first argument specifies the offset to start at and the second defines the number of rows to return, hence LIMIT 4,8 will return 8 rows (assuming there are 12 or more rows in the dataset).
The next issue is that you've not said if the results need to be reproducible - e.g. if you have rows with primary keys 1 and 2, should these always be returned in the same query. In the absence of an explicit ORDER BY clause, the rows will be returned based on the order in which they are found by the query.
The next issue is that you've not explained how you want to deal with the last case when the total number of rows is not an even multiple of 4.
The code you've provided counts the number of rows where ref = 'SB2004' but then creates queries which are not filtered - why?
The code you've provided does not change the limit in the queries - why?
The next issue is that there is never a good reason for running SELECT queries inside a loop like this. You didn't exlpain what you intend doing with the select queries. But based on the subsequent update....
include('connect.php');
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$cnt = mysql_fetch_assoc(mysql_query($query_1));
$blocks=$cnt['Total']/4 + (0 == $cnt['Total'] % 4 ? 0 : 1);
$qry2="SELECT * FROM prop where ref='SB2004' ORDER BY primary_key";
$res=mysql_fetch_assoc($qry2);
for ($x=0; $x<$blocks; $x++) {
print "<div>\n$block<br />\n";
for ($y=0; $y<4; $y++) {
print implode(",", #mysql_fetch_assoc($res)). "\n";
}
print "</div>\n";
}
It's trivial to refine this further to only issue a single query to the database.
If you really must generate individual SELECTs....
include('connect.php');
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$cnt = mysql_fetch_assoc(mysql_query($query_1));
$blocks=$cnt['Total']/4 + (0 == $cnt['Total'] % 4 ? 0 : 1);
for ($x=0; $x<$blocks; $x++) {
$y=$x*4;
print "SELECT * FROM prop where ref='SB2004'
ORDER BY primary_key LIMIT $y,4<br />\n"
}

Categories