PDO fetch and fetchAll with conditional statement not working

238 views Asked by At

his is not working can anyone help please?

(count($stmt->fetchAll()) > 1) ? $result = $stmt->fetchAll() : $result = $stmt->fetch();

print_r($result);
1

There are 1 answers

1
Mureinik On BEST ANSWER

All the fetchXYZ methods advance the underlying cursor, so once you've called them, you cannot "go back" and get the same rows again.

You could redo your condition in-memory, after calling fetchAll() only once:

$result = $statement->fetchAll();
if (count($result) == 1) {
    $result = $result[0];
}