How can I efficiently collect and pass multiple rows of data from a database to a view in PHP?
To efficiently collect and pass multiple rows of data from a database to a view in PHP, you can use a loop to fetch the data from the database and store it in an array. Then, pass this array to the view for rendering.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Pass the data to the view
include 'your_view.php';