How to display mysqli_query errors
P粉713846879
P粉713846879 2023-09-01 13:52:57
0
1
487
<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粉713846879
P粉713846879

reply all(1)
P粉538462187

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()
        ));
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!