What is the best practice for fetching multiple database entries in PHP and storing them in an array?
When fetching multiple database entries in PHP and storing them in an array, it is best practice to use a loop to iterate through the results and store each row in the array. This ensures that all the data is captured and organized properly for further processing.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Query to fetch multiple entries
$sql = "SELECT * FROM table_name";
$result = $mysqli->query($sql);
// Initialize an empty array to store the results
$data = array();
// Fetch rows and store them in the array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Close the connection
$mysqli->close();
// Output the array of fetched data
print_r($data);