How can PHP developers effectively debug and troubleshoot code errors related to database queries?

To effectively debug and troubleshoot code errors related to database queries in PHP, developers can use tools like var_dump() or print_r() to output the query results and check for any errors. They can also enable error reporting in PHP to display any errors that occur during the query execution. Additionally, developers can log errors to a file or use try-catch blocks to handle exceptions gracefully.

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

// Sample database query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

if(!$result) {
    die('Error: ' . mysqli_error($connection));
}

// Output query results
while($row = mysqli_fetch_assoc($result)) {
    echo $row['username'] . '<br>';
}

// Close database connection
mysqli_close($connection);