How can error handling be improved in PHP scripts that interact with a MySQL database to provide more informative feedback to developers during troubleshooting?
When interacting with a MySQL database in PHP scripts, error handling can be improved by utilizing the mysqli or PDO extension functions to capture and display detailed error messages. By checking for errors after each database operation, developers can receive informative feedback during troubleshooting.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform database query
$result = $mysqli->query("SELECT * FROM table");
// Check for errors
if (!$result) {
die("Query failed: " . $mysqli->error);
}
// Fetch results
while ($row = $result->fetch_assoc()) {
// Process results
}
// Close connection
$mysqli->close();