How can error handling be improved in the provided PHP code to prevent issues with database queries?
The issue with the provided PHP code is that it does not include proper error handling for database queries, which can lead to potential issues. To improve error handling, we can use try-catch blocks to catch any exceptions that may occur during the query execution and handle them accordingly.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users");
$stmt->execute();
while ($row = $stmt->fetch()) {
// Process fetched data
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Keywords
Related Questions
- How can the use of arrays improve the efficiency and readability of PHP code when working with database queries?
- What could be causing the "This server is currently overloaded" message when running a PHP script on Xitami server?
- How can the "Strict Standards: Only variables should be passed by reference" error be resolved in PHP?