What are the best practices for handling array data in PHP when fetching results from a database?
When fetching results from a database in PHP, it's important to handle the data properly, especially when dealing with arrays. To ensure data integrity and security, it's best practice to sanitize and validate the data before using it in your application. This can help prevent SQL injection attacks and ensure that the data is in the correct format for processing.
// Example of fetching data from a database and sanitizing the results
// Assume $conn is the database connection object
// Fetch data from the database
$query = "SELECT * FROM users";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// Initialize an empty array to store the results
$users = array();
// Loop through the results and sanitize each row
while ($row = $result->fetch_assoc()) {
// Sanitize the data using htmlspecialchars
$sanitizedData = array_map('htmlspecialchars', $row);
// Add the sanitized data to the users array
$users[] = $sanitizedData;
}
// Output the sanitized data
print_r($users);
} else {
echo "No results found";
}