How can error handling be improved when executing SQL queries in PHP to identify and resolve issues more effectively?
When executing SQL queries in PHP, error handling can be improved by enabling error reporting, using try-catch blocks to catch exceptions, and utilizing functions like mysqli_error() to retrieve detailed error messages. By implementing these practices, developers can identify and resolve issues more effectively.
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute SQL query
try {
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result === false) {
throw new Exception(mysqli_error($conn));
}
// Process query results
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Close connection
$conn->close();