How can you filter the result array after fetching data from a database in PHP based on a specific category?
When fetching data from a database in PHP, you can filter the result array based on a specific category by using a conditional statement to check each item's category. You can iterate over the result array and only include items that match the desired category in a new filtered array.
// Fetch data from the database
$query = "SELECT * FROM products";
$result = mysqli_query($connection, $query);
// Filter the result array based on a specific category
$category = "electronics";
$filteredResults = array();
while ($row = mysqli_fetch_assoc($result)) {
if ($row['category'] == $category) {
$filteredResults[] = $row;
}
}
// Output the filtered results
foreach ($filteredResults as $item) {
echo $item['name'] . " - " . $item['price'] . "<br>";
}
Related Questions
- Are there any best practices for handling echoing of variables in Smarty to avoid displaying arrays unintentionally?
- How can PHP developers efficiently handle data manipulation and calculations when dynamically removing records from a database query result set?
- Is it recommended to store shopping cart data in a database table or in $_SESSION variables for persistence and ease of access in PHP?