How can debugging techniques help identify errors in PHP code, especially when dealing with database queries?

Debugging techniques such as using print statements, var_dump, or error reporting can help identify errors in PHP code, especially when dealing with database queries. By outputting the values of variables, checking for syntax errors, and enabling error reporting, developers can pinpoint where the issue lies and make the necessary corrections.

// Enable error reporting
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 for connection errors
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Execute a sample database query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

// Check for query errors
if (!$result) {
    die("Query failed: " . $conn->error);
}

// Process the query results
while($row = $result->fetch_assoc()) {
    echo "Name: " . $row["name"];
}

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