How can you efficiently troubleshoot and debug errors related to database queries in PHP?

To efficiently troubleshoot and debug errors related to database queries in PHP, you can start by enabling error reporting and displaying error messages. Additionally, you can use functions like mysqli_error() to retrieve detailed error information from the database server. Finally, reviewing and verifying your SQL queries for syntax errors can help identify and resolve issues.

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Connect to the database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

// Check for connection errors
if ($mysqli->connect_error) {
    die('Connection failed: ' . $mysqli->connect_error);
}

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

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

// Check for query errors
if (!$result) {
    die('Error in query: ' . $mysqli->error);
}

// Fetch and display results
while ($row = $result->fetch_assoc()) {
    echo $row['username'] . '<br>';
}

// Close the connection
$mysqli->close();