What are common reasons for errors in querying a database using PHP?

Common reasons for errors in querying a database using PHP include syntax errors in the SQL query, incorrect database connection details, and improper handling of query results. To solve these issues, double-check the SQL query for any mistakes, ensure the database connection details are accurate, and properly handle query results to avoid errors.

// Example PHP code snippet to query a database with error handling

// 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);
}

// SQL query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

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

// Process query results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

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