How can conditional statements like "if" be effectively used to manage errors in PHP scripts accessing MySQL databases?
When accessing MySQL databases in PHP scripts, errors can occur due to various reasons such as connection issues, query syntax errors, or database server problems. To effectively manage these errors, conditional statements like "if" can be used to check for errors after executing database operations. By checking for errors and handling them appropriately, such as displaying error messages or logging them for further investigation, developers can ensure the smooth functioning of their PHP scripts.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check for connection errors
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a sample query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Check for query execution errors
if (!$result) {
die("Query failed: " . mysqli_error($connection));
}
// Process the query results
while ($row = mysqli_fetch_assoc($result)) {
// Do something with the data
}
// Close the database connection
mysqli_close($connection);