How can user details be retrieved using PHP based on user ID?
To retrieve user details based on user ID using PHP, you can query the database for the specific user record that matches the provided user ID. Once the record is fetched, you can access the user details such as username, email, etc. and display them as needed.
<?php
// Connect to 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 user details based on user ID
$user_id = 1; // Example user ID
$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 "Username: " . $row["username"]. "<br>";
echo "Email: " . $row["email"]. "<br>";
// Add more fields as needed
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are the best practices for securing PHP files that are included in other scripts to prevent unauthorized access or exploitation?
- How can arrays be effectively used in the scan_dir function in PHP to sort file listings?
- What are best practices for preventing SQL injection when using $_GET in PHP?