What are the best practices for securely retrieving and displaying user-specific data in PHP to prevent SQL injection vulnerabilities?

To securely retrieve and display user-specific data in PHP to prevent SQL injection vulnerabilities, you should always use prepared statements with parameterized queries to sanitize user input and prevent malicious SQL injection attacks. This involves binding parameters to placeholders in the SQL query, ensuring that user input is treated as data rather than executable code.

// Example of securely retrieving and displaying user-specific data using prepared statements

// Assume $userId is the user's input
$userId = $_GET['user_id'];

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind the user input to the parameter
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo $row['username'] . '<br>';
}