PDO, roll two queries in one?

Hi All,

I have a script which first runs a query, then runs another one to count how many queries are returned.

Question I have is am I making life hard for myself. Could this be rolled into one query?:


//SELECT DATA
$SEARCH_QUERY = "SELECT * FROM tbl"; 
$RES = $dbc->query($SEARCH_QUERY);
$name = $RES['name'];
$age = $RES['age'];

//COUNT DATA
$COUNT_QUERY = $dbc->query("SELECT COUNT(*) AS total FROM tbl");  
$COUNT_QUERY->setFetchMode(PDO::FETCH_ASSOC);   
$ROW = $COUNT_QUERY->fetch();	
$TOTALROWS = $ROW['total'];

// If no results in the database: 
if($TOTALROWS == 0) {
  echo $NUM_RES =  'Sorry, we have found no people in the database'; 
} else {
 echo 'We have found '.$NUM_RES.' people in the database';
}

sorry i don’t know anything about pdo, it was the two queries part that pulled me in :slight_smile:

if you retrieve rows from a query, most languages have some function or property like mysql_num_rows that tell you how many rows you got

Yes, of course thanks! It triggered my brain, sorted it now - thanks!


$SEARCH_QUERY = "SELECT * FROM tbl"; 
$RES = $dbc->query($SEARCH_QUERY);
$NUM_ROWS = $RES->fetchColumn();

// If no results in the database: 

if($NUM_ROWS == 0) {
  echo $NUM_RES =  'Sorry, we have found no people in the database'; 
} else {
 echo 'We have found '.$NUM_ROWS.' people in the database';
} 

Can anyone please shout if i’ve done this wrong?

Thanks

You’re doing it wrong. :stuck_out_tongue:

There’s some great advice in the user comments over in the manual page for [URL=“http://php.net/manual/en/pdostatement.rowcount.php”]PDOStatement->rowCount.

Anthony.