search

Home  >  Q&A  >  body text

How to display mysqli_query errors

<p>I am trying to display mysqli_error in my php script, if the query fails, I keep getting a black page, but on success, a response is returned, if the query fails, both mysqli_error($conn) and mysqli_errno($conn) Just shows a black page. This is my database connection script</p> <pre class="brush:php;toolbar:false;"><?php $ser = "test"; $user = "test"; $pass = "test"; $db="test"; $conn = mysqli_connect($ser, $user, $pass, $db); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?></pre> <p>My PHP Query</p> <pre class="brush:php;toolbar:false;"><?php include 'conn.php'; if ($conn) { $sql = "INSERT INTO tbl_users (userId, email, pass) VALUES ('$userId', '$email', '$pass')"; if (mysqli_query($conn, $sql)) { echo json_encode(array( "status" => "Ok", "message" => "Success", )); } else { echo json_encode(array( "status" => "Error", "message" => mysqli_error($conn), )); } }</pre> <p>If the query runs correctly, I am able to get a successful response, but if I use <strong>ini_set('display_errors', 1);</strong> once an error occurs, I get a blank page;< /strong> I get full page errors but I just want mysqli_error or mysqli_errno. </p>
P粉713846879P粉713846879458 days ago547

reply all(1)I'll reply

  • P粉538462187

    P粉5384621872023-09-02 11:56:45

    As of PHP 8.1, the default setting for mysqli error reporting is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT, which causes errors to throw exceptions instead of just returning false.

    If you want to check for errors in your code instead of getting exceptions, use

    mysqli_report(MYSQLI_REPORT_OFF);

    A better solution is to use exception handlers.

    if ($conn) {
        $sql = "INSERT INTO tbl_users (userId, email, pass) VALUES ('$userId', '$email', '$pass')";
        try {
            mysqli_query($conn, $sql);
            echo json_encode(array(
                "status" => "Ok",
                "message" => "Success",
            ));
        catch (mysqli_sql_exception $e) {
            echo json_encode(array(
                "status" => "Error",
                "message" => $e->getMessage()
            ));
        }
    }

    reply
    0
  • Cancelreply