How can PHP developers handle error handling and checking for empty result sets in MySQL queries effectively?
When handling error handling and checking for empty result sets in MySQL queries, PHP developers can use try-catch blocks to catch any exceptions thrown during query execution. To check for empty result sets, developers can use functions like mysqli_num_rows() to determine the number of rows returned by a query.
<?php
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check for connection errors
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Attempt to execute a query
try {
$result = mysqli_query($connection, "SELECT * FROM table");
if (mysqli_num_rows($result) > 0) {
// Process the results
while ($row = mysqli_fetch_assoc($result)) {
// Do something with the data
}
} else {
echo "No results found.";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Close the connection
mysqli_close($connection);
?>
Related questions
-
What potential pitfalls should be considered when using the GET method to retrieve form data in PHP?GET method form data PHP
-
PHPExcel lightweight alternatives
-
SQL injection file upload file path