How can arrays be effectively used in PHP to store and manage data retrieved from MySQL queries?
To effectively store and manage data retrieved from MySQL queries in PHP, arrays can be used to organize and manipulate the data. By fetching the results of a query into an array, you can easily iterate through the data, access specific elements, and perform various operations on the dataset.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Execute a MySQL query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Fetch data into an array
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
// Access and manipulate data in the array
foreach ($data as $row) {
echo $row['column_name'] . "<br>";
}
// Close the connection
mysqli_close($connection);