What are the best practices for handling SQL errors and debugging PHP scripts that interact with a database?

When handling SQL errors in PHP scripts that interact with a database, it is important to use try-catch blocks to catch exceptions and handle them appropriately. Additionally, using error handling functions like mysqli_error() can help in debugging SQL queries. It is also recommended to log errors to a file or display them in a user-friendly manner to aid in troubleshooting.

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

// Execute the query
try {
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        // Output data
        while($row = $result->fetch_assoc()) {
            echo "Name: " . $row["name"];
        }
    } else {
        echo "0 results";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

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