How can PHP developers effectively troubleshoot errors related to SQL queries and database interactions in their scripts?

To effectively troubleshoot errors related to SQL queries and database interactions in PHP scripts, developers can use error handling techniques such as try-catch blocks to catch and display any SQL errors that occur during execution. Additionally, developers can enable error reporting in PHP settings to get detailed error messages that can help identify the root cause of the issue.

<?php
// Enable error reporting for debugging purposes
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Establish a database connection
$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);
}

// Sample SQL query with error handling
try {
    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);

    if ($result === false) {
        throw new Exception("Error: " . $conn->error);
    }

    // Process the query result
    while ($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

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