The mysqli_error() function in PHP is used to retrieve the last error message from the MySQL database connection. It returns a string that describes the last error that occurred during a query execution. If no error occurred, it will return an empty string.
Syntax:
mysqli_error(connection);
- connection: The MySQLi connection object (returned by
mysqli_connect()).
Example Usage:
- Basic Example:
This example demonstrates using
mysqli_error() to capture and display errors that occur during a database query.
<?php
// Create connection
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Incorrect SQL query to trigger an error
$sql = "SELECT * FROM non_existing_table";
$result = mysqli_query($conn, $sql);
// Check for errors
if (!$result) {
echo "Error: " . mysqli_error($conn); // Display MySQL error message
}
mysqli_close($conn);
?>
Explanation:
- In this example, the query is incorrect because it references a table that doesn't exist (
non_existing_table).
- The
mysqli_error() function captures and displays the error message from MySQL (e.g., "Table 'database.non_existing_table' doesn't exist").
- With Prepared Statements:
Here’s how you can use
mysqli_error() when working with prepared statements.
<?php
// Create connection
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Prepare a query with an error in it
$query = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = mysqli_prepare($conn, $query);
if (!$stmt) {
echo "Prepared Statement Error: " . mysqli_error($conn); // Check if prepare failed
}
// Bind parameters and execute
$name = 'John Doe';
$email = 'john.doe@example.com';
mysqli_stmt_bind_param($stmt, 'ss', $name, $email);
if (!mysqli_stmt_execute($stmt)) {
echo "Execute Error: " . mysqli_error($conn); // Check if execution failed
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
Explanation:
- The example uses prepared statements to insert a user into the
users table.
- If any error occurs during the preparation or execution of the query,
mysqli_error() captures and displays the MySQL error message.
Key Points:
mysqli_error() helps in debugging by providing error messages from the MySQL server.
- It is often used after a query or prepared statement execution to check for errors and handle them accordingly.
- Always ensure to handle errors properly in a production environment, possibly using custom error handling mechanisms.