How can the code be modified to handle errors more effectively when interacting with a MySQL database?
When interacting with a MySQL database, it is important to handle errors effectively to prevent unexpected behavior or security vulnerabilities. One way to do this is by implementing error handling using try-catch blocks in PHP. By wrapping database queries within a try block and catching any exceptions that may occur, you can handle errors gracefully and display appropriate error messages to the user.
<?php
// Connect to MySQL database
$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);
// Perform database query
$stmt = $conn->prepare("SELECT * FROM table");
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display results
foreach($results as $row) {
echo $row['column'] . "<br>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Close database connection
$conn = null;
?>