How can error reporting and error handling be improved to troubleshoot issues with database queries in PHP?
To improve error reporting and handling for database queries in PHP, you can use the try-catch block to catch any exceptions thrown during query execution. Additionally, you can set the error mode of the PDO object to PDO::ERRMODE_EXCEPTION to ensure that exceptions are thrown when errors occur.
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM mytable");
$stmt->execute();
while ($row = $stmt->fetch()) {
// Process each row here
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}