How can PHP arrays be utilized to efficiently manage and display database entries?
PHP arrays can be utilized to efficiently manage and display database entries by fetching the data from the database and storing it in an array. This allows for easy manipulation and organization of the data before displaying it on a webpage. By using PHP array functions, such as foreach loops, you can iterate through the array and display the database entries in a structured and visually appealing manner.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "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 table";
$result = $conn->query($sql);
// Store database entries in an array
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Display database entries using a foreach loop
foreach($data as $entry) {
echo "ID: " . $entry['id'] . " - Name: " . $entry['name'] . "<br>";
}
// Close database connection
$conn->close();