What are the best practices for handling database errors in PHP?
When handling database errors in PHP, it is important to implement error handling to gracefully manage any issues that may arise during database operations. This includes catching and logging errors, providing informative error messages to users, and taking appropriate actions based on the type of error encountered.
// Connect to the database
$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);
}
// Perform database operations
// Example query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Check for query errors
if (!$result) {
die("Error: " . $conn->error);
}
// Process query results
while ($row = $result->fetch_assoc()) {
// Process each row
}
// Close the connection
$conn->close();