How can you use a while loop to fill an array in PHP with data from a database table?
To fill an array in PHP with data from a database table using a while loop, you can fetch the data from the database using a query and then iterate over the result set using a while loop to populate the array. Inside the while loop, you can fetch each row of data and add it to the array until all the data is processed.
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch data from the database table
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Initialize an empty array to store the data
$dataArray = array();
// Use a while loop to iterate over the result set and fill the array
while ($row = mysqli_fetch_assoc($result)) {
$dataArray[] = $row;
}
// Close the database connection
mysqli_close($connection);
// Display the data in the array
print_r($dataArray);
Keywords
Related Questions
- In what scenarios would it be recommended to use JavaScript to send POST data instead of traditional form submission in PHP?
- What potential issues can arise when submitting URLs with special characters like double slashes in PHP forms?
- How does the use of class aliases in PHP impact autoloading and class loading mechanisms within a project?