From what I know now about PDO statements and my own experiences on localhost and Google – there are some difficulties with using multiple PDO statements in one query. For instance this situation:
$stmt = $db_people->prepare("SELECT * FROM people WHERE online=1");
$stmt->execute();
$results_people = $stmt->fetch(PDO::FETCH_ASSOC);
On this query I can do simple PDO statement like fetch (in example). But when I want to use PDO statement like this:
$rows = $stmt->rowCount();
It is not possible and the statement will not return the right number of rows. When I do it in the other way around and filling one of the column name – rowCount works correctly like this:
$stmt = $db_people->prepare("SELECT name FROM people WHERE online=1");
$stmt->execute();
$rows = $stmt->rowCount();
And adding fetch after that like this:
$results_people = $stmt->fetch(PDO::FETCH_ASSOC);
Will not work corectly in this example. My question is – How to combine two different PDO statements in one single query? Thank you.
The answer probably depends on which operations you’re trying to combine. For instance, if you’re trying to combine
PDOStatement::rowCount()with aSELECTSQL operation, then it’s probably worthwhile to take notice of the warnings in thePDOStatement::rowCount()description which says thatrowCount()is not 100% reliable for SELECT statements in all databases.If the problem you’re trying to solve is specifically limited to counting the result rows of a SELECT, then another approach would be to use
PDOStatement::fetchAll()and count the rows in the returned array.