How can PHP be utilized to retrieve user data from a database after successful authentication for features like a shoutbox?
To retrieve user data from a database after successful authentication for features like a shoutbox, you can use PHP to query the database based on the authenticated user's credentials. This involves connecting to the database, executing a SELECT query to fetch the user's information, and then displaying or using that data in your application.
// Assuming the user is already authenticated and their ID is stored in a variable like $user_id
// 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);
}
// Query the database for user data
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "User ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();