teelou teelou - 2 months ago 11
MySQL Question

How to return false if 0 rows affected with PDO?

How can I return false if 0 rows affected with PDO?

I have this method to execute a SQL query,

public function executeSQL($query, $params = array())
{

try
{
$stmt = $this->connection->prepare($query);
$params = is_array($params) ? $params : array($params);
$stmt->execute($params);
return true;

}
catch (PDOException $e)
{
// call the get_error function
$this->get_error($e);
}
}


So I can run a query like this below for updating a row in my table,

$update = "
UPDATE content_has_language
SET text = ?
WHERE content_id ?
AND language_id IN
(
SELECT language_id
FROM language AS l
WHERE l.code = ?
)
";

$result = $this->connection->executeSQL($update,array(
'xxx',
'1',
'en'
));


And it always return true whether the row is matched and updated or not. But I need it to return false - if
0 rows affected. (Query took 0.0010 sec)


Is it possible?

Answer

Try this

return $stmt->rowCount() > 0;
Comments