I have a PDO function:
function(){
$success=$this->query($query, $bindvalues);
return ($success == true) ? $this->stmt->fetch(PDO::FETCH_ASSOC) : false;
}
When I perform a select query that returns a row (or more), it will return for example:
array(1) { ["Id"]=> string(1) "1" }
When the query fails (if I have a wrong syntax for example), it will return FALSE.
But if no rows are found with the query it also returns FALSE.
So the return value with an error in the query and with no rows will both return FALSE. How is that possible? I need to return FALSE only when there is an error in the query, and I need to return NULL for example when there are no results. Is there something wrong in my function?
Thanks!
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.
Return Values ¶ PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0 . This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .
Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.
If no row was found PDO::fetch returns false. This is a fact. So change your function:
function(){
$success = $this->query($query, $bindvalues);
if(!$success) {
//handle error
return false;
}
$rows = $this->stmt->fetch(PDO::FETCH_ASSOC);
return $rows ?: null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With