Currently when there is an error with my SQL it throws the traditional error that looks like this:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax...|
I know I can achieve what I want by wrapping every SQL routine in a try/catch block but this seems a little long winded:
class ProductsModel extends Model {
function __construct()
{
parent::__construct();
}
public function setName($name, $productId)
{
$SQL = 'UPDATE products SET name = ? WHERE id = ?';
try{
$r = $this->db->prepare($SQL);
$r->execute(array($name, $productId));
}catch(PDOException $e) {
echo 'Error!';
}
}
}
Is there a way to have this done automatically for all SQL queries made?
Yes there is, and no, you shouldn't do it.
What you should do, is not to catch it inside the function, and instead, wrap the method call inside of the higher level with the catch block. i.e.:
try {
$productsModel->setName("name", 42);
}
catch (PDOException $e) {
//Do something, 500 error code, whatever
}
That's because, only when you try to access the database you know what you want to do in case it fails.
This:
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