In what scenarios would it be more beneficial to use a database instead of arrays in PHP for storing and manipulating data?
Using a database would be more beneficial than arrays in PHP when dealing with large amounts of structured data that require complex querying, sorting, and filtering operations. Databases offer better performance, scalability, and data integrity compared to arrays. Additionally, databases provide features like indexing, transactions, and relationships that are essential for managing data effectively.
// Connect to a MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Insert data into a table
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
$conn->query($sql);
// Retrieve data from a table
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();