What are the best practices for handling database query results in PHP to ensure accurate data retrieval?
When handling database query results in PHP, it is important to properly handle errors, sanitize input to prevent SQL injection attacks, and use prepared statements to ensure accurate data retrieval. Additionally, always check for the number of rows returned before processing the results to avoid errors.
// Example of handling database query results in PHP
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare and execute the query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
// Check for errors
if ($stmt->error) {
die("Query failed: " . $stmt->error);
}
// Check the number of rows returned
if ($stmt->num_rows > 0) {
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
echo "Name: " . $row['name'] . "<br>";
}
} else {
echo "No results found.";
}
// Close the statement and connection
$stmt->close();
$mysqli->close();