count rows in table with many different parameters

最后都变了- 提交于 2019-12-24 21:58:12

问题


I know that I can count how many rows have a certain string in the columns of my table like this...

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

$inClass101rows reflects the number of rows in my database with $timeOfClass as W-7PM-A.

But how can I do this for multiple variables of the $timeOfClass string without writing multiple SQL statements? I have a lot of them. Would this be something like make an array of SQL statements and then run them through a while loop of fetchColumn(0) ?


回答1:


<?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);

Use SQL to alter the result as you which, e.g. add a GROUP BY clause to get several counts for looping.




回答2:


Are you trying to do this for several values of $timeOfClass?

You could put all of the $timeOfClass variables in an array (W-7PM-A,W-8PM-A,etc..) then use an sql like this:

SELECT count(*) FROM students WHERE timeOfClass IN ('W-7PM-A','W-8PM-A',...) GROUP BY timeOfClass

This would give you one SQL query that you can loop through the rows to get the individual counts.




回答3:


where timeofclass in ("value 1, 'value 2'); is the right sql syntax. You can take your array of times and create the in clause and concatenate it onto the end of your statement. you could also create a stored proc that handles the query and takes a CSV of values as a parameter. HTH



来源:https://stackoverflow.com/questions/21689646/count-rows-in-table-with-many-different-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!