How can prepared statements and secure database access be implemented in PHP to retrieve and display user data on profile pages?

To implement prepared statements and secure database access in PHP to retrieve and display user data on profile pages, you should use parameterized queries to prevent SQL injection attacks. This involves binding user input to placeholders in the SQL query before execution. Additionally, make sure to properly sanitize and validate user input to further enhance security.

// Establish database connection
$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 data using prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);

$userId = $_GET['user_id']; // Assuming user_id is passed as a parameter

$stmt->execute();
$result = $stmt->get_result();

// Display user data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"] . "<br>";
        echo "Email: " . $row["email"] . "<br>";
        // Add more fields as needed
    }
} else {
    echo "No user found";
}

$stmt->close();
$conn->close();