我知道我可以像这样计算表的列中有多少行有某个字符串......
$timeOfClass="W-7PM-A";
$inclass101 = $db->prepare("SELECT count(*) FROM students WHERE timeOfClass =?");
$inclass101->execute(array($timeOfClass));
$inclass101rows = $inclass101->fetchColumn(0);
$inClass101rows
反射(reflect)了我的数据库中 $timeOfClass
为 W-7PM-A
的行数。
但是,如何在不编写多个 SQL 语句的情况下对 $timeOfClass
字符串的多个变量执行此操作呢?我有很多。这是否类似于创建一个 SQL 语句数组,然后通过 fetchColumn(0)
的 while 循环运行它们?
最佳答案
<?php
// $timesOfClasses is an array in the form:
$timesOfClass = array(
"W-7PM-A",
"X-8AM-Y",
"...",
);
// Generate the IN clause safely for usage with prepared statements
$params = substr(str_repeat("?,", count($timesOfClass)), 0, -1);
$inclass101 = $db->prepare("SELECT COUNT(*) FROM `students` WHERE `timeOfClass` IN({$params})");
$inclass101->execute($timesOfClass);
$inclass101rows = $inclass101->fetchColumn(0);
使用 SQL 来更改结果,例如添加 GROUP BY
子句以获取循环计数。
关于php - 计算具有许多不同参数的表中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689646/