php - 计算具有许多不同参数的表中的行数

标签 php mysql sql pdo

我知道我可以像这样计算表的列中有多少行有某个字符串......

  $timeOfClass="W-7PM-A";
  $inclass101 = $db->prepare("SELECT count(*) FROM students WHERE timeOfClass =?");
  $inclass101->execute(array($timeOfClass));
  $inclass101rows = $inclass101->fetchColumn(0);

$inClass101rows 反射(reflect)了我的数据库中 $timeOfClassW-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/

相关文章:

php - 使用自定义参数导出数据 Laravel Excel

php - 使用 get_post_meta 将 unix 时间戳改回 mysql 日期时间

PHPUnit - 当 processIsolation 设置为 false 时无法重新声明类

php - MySQL 将行计数为一

sql - 如何在 MS Access 中正确使用 "Not Equal"?

mysql - 从两行中,返回包含数字/字符串字符的行

php - 无法在一个查询中的多个查询上使用聚合函数

php - 另一个不起作用的动态表(搜索引擎)

sql - select * from table where datetime in month(不破坏索引)

mysql - 如何删除数据库中的外键?