How can an array be effectively used in PHP to store and manipulate data retrieved from database queries?
To effectively store and manipulate data retrieved from database queries in PHP, an array can be used to hold the results. Each row of data fetched from the database can be stored as an associative array within the main array. This allows for easy access and manipulation of the data using array functions and loops.
// Assume $db is the database connection object
// Retrieve data from the database
$query = "SELECT * FROM table_name";
$result = $db->query($query);
// Initialize an empty array to store the fetched data
$data = [];
// Fetch and store each row of data as an associative array in the main array
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
// Now $data contains all the fetched data and can be manipulated as needed
Keywords
Related Questions
- How can a database be integrated into PHP to handle user permissions and access rights effectively?
- What are best practices for structuring and organizing PHP code to handle hierarchical data like user relationships?
- How can data from a database text field be passed to an include without writing to a file?