In my program I want update some information, so I used:
return ($result->rowCount() == 1)? true: false;
this way, if you save information without any change, false
is returned and this is not the result usually we expect.
I change my function to this one
try{
$result=$db->prepare($sql);
$result->execute($arr);
return true;
}catch(Exception $e){
return false;
}
Is it the best way? Does this way guarantee that the update statement worked or not?
Assuming your $db
is instance of PDO
When you run PDO::prepare
you can detect sql syntax error and when you run PDO::execute
you will be sure that syntax is correct. Then application is resposible for knowing if update should have updated something or not.
So here is some sample code:
function update($db, $sql)
{
$preparedSql = $db->prepare($sql);
if(!$preparedSql) {
// syntax error occured
$errorInfo = $db->errorInfo();
// handle error
return false;
}
$db->execute($preparedSql);
// note that rowCount returns 0 when none updated
return $db->rowCount();
}
In your application
$result = update($db, $sql);
if($result === false)
{
// error occured
} elseif($result === 0) {
// zero rows updated
} else {
// some rows were updated
}
Note that it's not tested and for learning purposes only, update
function should accept to bind parameters for real world application