简体   繁体   中英

SQL, PDO, and PHP - Conditioned rowCount() function

I am running the following SQL PDO command in an Apache PHP server page:

$query = "
    SELECT
        id,
        building_name
    FROM
        campus
";

$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();          // HERE IS THE FUNCTION

Instead of returning the entire row count I'd like the rowCount() function to return only the number of rows where "building_name" = "IT House". I can't seem to find any information about this function, such as which arguments it expects, etc. Any idea how I can modify the function call in the assignment operation? Thanks in advance!

NOTE: I know I can condition the query via SELECT command, but I don't want to limit my query there. I need the query to represent all rows, but I need rowCount to only represent the desired rows.

You can find the documentation for rowCount here: http://php.net/manual/en/pdostatement.rowcount.php

Is there something else you are doing with the result that precludes you from only selecting rows with that condition?:

SELECT id, building_name FROM campus WHERE building_name = 'IT House'

Better yet you can just select the count:

SELECT COUNT(*) FROM campus WHERE building_name = 'IT House'

Otherwise you have to loop through the results to determine the number of rows that meet your condition:

$stmt->execute();
$result = $stmt->fetchAll();
$num = 0;
foreach($result as $row) {
  if( 'IT House' == $row['building_name'] ) {
    $num++;
  }
}

如果您不想在SQL语句中添加条件,则需要遍历所有结果,然后根据building_name是否等于IT House来增加一个计数器

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