How can the code be modified to display error messages in case of database connection or query failures?
To display error messages in case of database connection or query failures, you can use PHP's try-catch block to catch any exceptions thrown by the database connection or query execution. Within the catch block, you can then display the error message to the user.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table_name");
$stmt->execute();
while ($row = $stmt->fetch()) {
// Process the fetched data
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Related Questions
- In what scenarios would it be more efficient to copy an image onto a white background or overlay a white rectangle to adjust opacity in PHP?
- What are the best practices for ensuring that numbers are displayed in their full format rather than in scientific notation in PHP applications?
- What are the limitations of using PHP to display real-time online user activity on a website?