← Back to Chapters

PHP MySQLi Error Functions

? PHP MySQLi Error Functions

? Quick Overview

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.

? Key Concepts

  • Connection Errors occur when the database server is unreachable or credentials are invalid.
  • Query Errors happen due to invalid SQL syntax or missing tables/columns.
  • Error Codes help identify the exact reason behind a failure.

? Syntax / Theory

  • mysqli_error() returns the last error description.
  • mysqli_errno() returns the numeric error code.
  • mysqli_sqlstate() returns the standardized SQLSTATE code.

? Code Example

? View Code Example
// 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();
?>

? Live Output / Explanation

The query fails because SELECT is misspelled as SELEC. MySQLi detects this syntax error and returns:

  • A descriptive error message
  • A numeric error code
  • A standardized SQLSTATE value

? Interactive Concept

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.

?️ Use Cases

  • Debugging database connection issues during development
  • Logging SQL errors for later analysis
  • Conditionally handling different database failures

✅ Tips & Best Practices

  • Always check for errors after executing MySQLi queries.
  • Log errors instead of displaying them in production.
  • Combine error handling with prepared statements for better security.

? Try It Yourself

  • Create different SQL errors and compare error codes.
  • Write a script that logs MySQLi errors to a file.
  • Test with both valid and invalid database credentials.