How can one implement error handling in PHP when working with database queries, especially with deprecated functions like mysql_?
When working with database queries in PHP, especially with deprecated functions like mysql_, it is essential to implement error handling to ensure the stability and security of your application. One way to handle errors is by using try-catch blocks to catch exceptions thrown by database operations and display appropriate error messages to the user.
try {
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
throw new Exception("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result === false) {
throw new Exception("Error: " . $conn->error);
}
// Process the query result here
$conn->close();
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
Related Questions
- How does separating design and program logic enhance code quality in PHP applications?
- What is the best practice for storing images in a separate folder and writing data to a database in PHP?
- In the given PHP code, how can conditional statements be used to display specific fields only if they are filled with data?