How can errors be properly handled and displayed when working with mysqli queries in PHP?
To properly handle and display errors when working with mysqli queries in PHP, you can use the `mysqli_error()` function to retrieve the error message if a query fails. This can help in debugging and troubleshooting any issues that may arise during query execution.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform a query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
// Check for errors
if (!$result) {
echo "Error: " . $mysqli->error;
}
// Display results
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
}
// Close connection
$mysqli->close();
Related Questions
- What is the significance of the error "Cannot modify header information - headers already sent" in PHP?
- Are there any best practices or alternative approaches to achieve real-time content updates in PHP without relying heavily on JavaScript?
- What are common issues when sending HTML emails with PHP, and how can they be resolved?