When working with MySQLi in PHP, handling errors is essential to ensure that your application behaves as expected, especially in case of issues like connection failures, query errors, or invalid syntax. MySQLi provides several functions to retrieve and handle errors that occur during database operations.
// Create MySQLi connection and demonstrate error handling
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername,$username,$password,$dbname);
// Check database connection error
if($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
}
// Intentionally incorrect SQL to trigger an error
$sql = "SELEC * FROM users";
$result = $conn->query($sql);
// Handle query error using MySQLi error functions
if($result === FALSE){
echo "Error: ".$conn->error."<br>";
echo "Error Code: ".$conn->errno."<br>";
echo "SQLSTATE: ".$conn->sqlstate."<br>";
}else{
echo "Query executed successfully!";
}
$conn->close();
?>
The query fails because SELECT is misspelled as SELEC. MySQLi detects this syntax error and returns:
Try changing the SQL query to a valid one (for example, SELECT * FROM users) and observe that no error messages are displayed. Then reintroduce different mistakes (wrong table name, missing column) to see how the error details change.