1

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

2
  • 2
    You have two calls to $stmt->execute() Commented Dec 28, 2020 at 22:25
  • Also odd you're emitting HTML in a cron job. Commented Dec 28, 2020 at 22:36

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.