How to Returns the last error code for the most recent function call (MySQLi) in PHP ?


In MySQLi, we can use the mysqli_errno() function to return the error code for the most recent function call. Here are the different methods to do it:

Method 1: Using mysqli_errno() function

// Create a connection
$conn = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection is successful
if (!$conn) {
    // If connection fails, get the error code and message
    $error_code = mysqli_errno($conn);
    $error_message = mysqli_error($conn);

    // Display the error code and message
    echo "Error code: " . $error_code . "<br>";
    echo "Error message: " . $error_message;
}

// Close the connection
mysqli_close($conn);

Method 2: Using mysqli_connect_errno() function

// Create a connection
$conn = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection is successful
if (mysqli_connect_errno()) {
    // If connection fails, get the error code and message
    $error_code = mysqli_connect_errno();
    $error_message = mysqli_connect_error();

    // Display the error code and message
    echo "Error code: " . $error_code . "<br>";
    echo "Error message: " . $error_message;
}

// Close the connection
mysqli_close($conn);

Method 3: Using mysqli_error_list() function

// Create a connection
$conn = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection is successful
if (!$conn) {
    // If connection fails, get the error list
    $error_list = mysqli_error_list($conn);

    // Loop through the error list and display the error code and message
    foreach ($error_list as $error) {
        echo "Error code: " . $error['errno'] . "<br>";
        echo "Error message: " . $error['error'] . "<br>";
    }
}

// Close the connection
mysqli_close($conn);


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.