Reputation: 513
I have a PHP script that is executed daily by my server thanks to cron. This script contains PDO queries to add, edit, and delete data from my MySQL database. The script does not work as expected, especially the last part of the query which is supposed to remove some rows:
$stmt = $conn->prepare("DELETE FROM `mkgaction` WHERE score IS NULL");
$stmt->execute();
if($stmt->execute()) {
echo "delete succeeded<br>";
} else {
echo "delete failed<br>";
}
When executed manually via PHPMyAdmin, every query works fine. When executed via this script it does not work despite the message showing "delete succeeded". I suppose the best way to understand what actually happens is to read the response from the database, but I don't know how to do that. Would you help me? :-) Thanks
Upvotes: 1
Views: 155
Reputation: 562661
Always check the return value of prepare()
and execute()
. They return the boolean value false if there's a problem.
Then you should check the specific error and report that error to help debugging.
$stmt = $conn->prepare("DELETE FROM `mkgaction` WHERE score IS NULL");
if ($stmt === false) {
die(print_r($conn->errorInfo(), true));
}
$ok = $stmt->execute();
if ($ok === false) {
die(print_r($stmt->errorInfo(), true));
}
echo "delete succeeded<br>";
Admittedly, checking every call gets to be a lot of repetitive code. An alternative is to enable exceptions, if you're comfortable writing code to handle exceptions. See https://www.php.net/manual/en/pdo.error-handling.php
Upvotes: 2