Current Location: Home> Latest Articles> Write database error assertions using mysqli_stmt::$error

Write database error assertions using mysqli_stmt::$error

gitbox 2025-05-28

Database operations are an inevitable part of developing PHP applications, especially when interacting with a MySQL database. Whether it is inserting, updating, deleting, or querying data, any error in any step can cause application failure or data inconsistency. In order to ensure the smooth execution of database operations, we need an effective error handling mechanism.

mysqli_stmt::$error is a very useful property provided by the PHP MySQLi extension, which allows us to get error information that occurred in the last database operation. In this article, we will discuss how to use mysqli_stmt::$error to write database error assertions and effectively handle errors in database operations.

1. Connect to the database

Before we start writing database operations, we first need to connect to the MySQL database through mysqli . We can connect through mysqli_connect() or object-oriented method.

 <?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test_db';

// Create connections using an object-oriented approach
$mysqli = new mysqli($host, $user, $password, $database);

// Check if the connection is successful
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}
?>

2. Use mysqli_stmt to execute SQL query

Once we successfully connect to the database, the next step is to prepare the SQL query. For effective error handling, it is recommended to use prepared statements. Preprocessing statements not only prevent SQL injection, but also improve query efficiency.

Here is how to use mysqli_stmt to execute SQL queries and handle possible errors:

 <?php
$sql = "INSERT INTO users (username, email) VALUES (?, ?)";

// Use preprocessing statements
$stmt = $mysqli->prepare($sql);

if ($stmt === false) {
    die("Preprocessing statement error: " . $mysqli->error);
}

// Bind parameters
$username = 'john_doe';
$email = '[email protected]';
$stmt->bind_param('ss', $username, $email);

// Execution statement
$stmt->execute();

// Check the execution results
if ($stmt->error) {
    die("Execution error: " . $stmt->error);
} else {
    echo "Data insertion successfully!";
}
?>

3. Error assertion and exception handling

During development, error assertions are very important and help us quickly locate and resolve problems. We can combine mysqli_stmt::$error to make error assertions. When the database operation fails, stop the program immediately and output specific error information.

 <?php
function assertQuerySuccess($stmt) {
    if ($stmt->error) {
        throw new Exception("Database operation failed: " . $stmt->error);
    }
}

try {
    $sql = "INSERT INTO users (username, email) VALUES (?, ?)";
    $stmt = $mysqli->prepare($sql);
    assertQuerySuccess($stmt); // If there is an error,throw an exception

    $username = 'jane_doe';
    $email = '[email protected]';
    $stmt->bind_param('ss', $username, $email);
    $stmt->execute();

    assertQuerySuccess($stmt); // 再次Check the execution results
    echo "Data insertion successfully!";
} catch (Exception $e) {
    echo "mistake: " . $e->getMessage();
}
?>

In the above code, the assertQuerySuccess() function checks whether the database operation is successful. If the operation fails, it throws an exception, which we can catch and process accordingly if needed.

4. Handle different error types

Sometimes, there may be many reasons for database operations to fail. For example, it could be a SQL syntax error, a database connection problem, or a server failure. By checking the error message in the mysqli_stmt::$error property, we can take corresponding measures based on different error types.

 <?php
if ($stmt->error) {
    // 处理特定的mistake
    switch ($stmt->errno) {
        case 1062:
            echo "mistake:Duplicate entries!";
            break;
        case 1049:
            echo "mistake:Unknown database!";
            break;
        default:
            echo "数据库mistake: " . $stmt->error;
    }
}
?>

5. Summary

Using mysqli_stmt::$error for database error handling can effectively help us locate problems and ensure that our applications can respond quickly and take appropriate measures when the database operation fails. Through good error assertion and exception handling mechanisms, the robustness and maintainability of the program have been significantly improved.

In this article, we describe how to use mysqli_stmt::$error for error assertions, how to handle common errors in database operations, and further enhance the robustness of the code through exception handling. Hopefully this article will help you better handle database-related errors in your PHP project.