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();
?>