Search code examples
phpmysqlexceptionmysqli

How to catch one specific mysql error in mysqli?


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?


Solution

  • 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;
        }
    }