What are the best practices for querying a database in PHP to avoid displaying incorrect information?

When querying a database in PHP, it is important to sanitize user input to prevent SQL injection attacks and ensure the accuracy of the data being displayed. One way to achieve this is by using prepared statements with parameterized queries. This helps separate the SQL query logic from the user input, reducing the risk of displaying incorrect information.

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

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

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

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

// Fetch the results
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Display the user information
echo "User ID: " . $user['id'] . "<br>";
echo "Username: " . $user['username'] . "<br>";
echo "Email: " . $user['email'] . "<br>";