简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM