0

I've got a mysqli_query inside a try block like below:

    try {
        mysqli_query($db,$sql);
    }
    catch (Exception $e) {
        throw $e;
    }

I'm trying to catch a "PHP Fatal error: Uncaught mysqli_sql_exception: Data too long for column ..." error so I can display a PHP message on the page. At the moment since it's a fatal error it just crashes the script and I can't display anything.

I've tried putting mysqli_query($db,$sql); in a try catch block but the issue persists. I've read elsewhere that setting mysqli_report(MYSQLI_REPORT_ALL); might help, I've tried putting that before the query but it doesn't change anything.

Any ideas?

0

1 Answer 1

-2

It's a rare case when using try catch around SQL query execution is justified.

In order to handle one specific SQL error, you may add a condition inside the catch block that is looking for the specific error, either using getCode() or getMessage(), and then, if found, handle it the way you like. While using throw $e; otherwise, so all other errors will be handled the usual way elsewhere:

try {
    mysqli_query($db,$sql);
}
catch (mysqli_sql_exception $e) {
    if (str_starts_with($e->getMessage(),"Data too long for column")) {
        // handle the error
    } else {
        throw $e;
    }
}
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.