What are the advantages of using associative arrays to retrieve and display data from a MySQL query in PHP?
When retrieving data from a MySQL query in PHP, using associative arrays allows for easier and more intuitive access to the data. Associative arrays use key-value pairs, making it simple to retrieve specific columns by their names. This can make the code more readable and maintainable compared to using numerical indexes.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Perform query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Fetch data using associative array
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row['name'] . ", Age: " . $row['age'] . "<br>";
}
// Close connection
mysqli_close($connection);