In what scenarios would using a database be a more suitable solution than PHP for managing and displaying data?
Using a database would be a more suitable solution than PHP for managing and displaying data when dealing with large amounts of structured data that needs to be efficiently stored, queried, and updated. Databases provide better scalability, security, and data consistency compared to managing data solely with PHP scripts.
// Connect to a MySQL 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);
}
// Retrieve data from database and display
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();