How can mysqli_fetch_assoc() be used effectively to handle database results in PHP?
When fetching results from a MySQL database in PHP, the mysqli_fetch_assoc() function can be used effectively to retrieve rows as associative arrays. This allows for easier access to data using column names as keys. To handle database results efficiently, loop through the result set using mysqli_fetch_assoc() until all rows have been fetched.
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Fetch and output results as associative arrays
while ($row = mysqli_fetch_assoc($result)) {
echo $row['column1'] . " - " . $row['column2'] . "<br>";
}
// Close the connection
mysqli_close($connection);
Related Questions
- How can PHP be used to validate form inputs directly on the page without redirecting to another page?
- What are some alternative methods to fopen for reading large text files in PHP, and how can developers optimize file reading performance for files over 0.5 MB in size?
- What is the purpose of using fopen with the "w+" mode in PHP?