How can displaying both error messages and SQL queries help in debugging PHP code that interacts with a database?

Displaying both error messages and SQL queries can help in debugging PHP code that interacts with a database by providing more detailed information about what went wrong. Error messages can point out syntax errors or connection issues, while SQL queries can show the exact query being executed, helping to pinpoint any mistakes in the database interactions.

<?php
// Enable error reporting and display errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Connect to the database
$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);
}

// Example SQL query
$sql = "SELECT * FROM users WHERE id = 1";

// Display the SQL query
echo "SQL Query: " . $sql . "<br>";

// Execute the SQL query
$result = $conn->query($sql);

// Check for errors
if (!$result) {
    echo "Error: " . $conn->error;
}

// Close the connection
$conn->close();
?>