How can PHP variables be used to store data retrieved from a database and displayed to users?
To store data retrieved from a database and display it to users using PHP variables, you can first fetch the data from the database using SQL queries and store it in PHP variables. Then, you can use these variables to display the data on the webpage using HTML or echo statements.
<?php
// 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 data in PHP variables
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row["name"];
$email = $row["email"];
}
} else {
echo "0 results";
}
// Display data to users
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
// Close the connection
$conn->close();
?>