What is the correct way to use prepared statements in PHP?

When working with databases in PHP, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to execute queries. To use prepared statements in PHP, you can use the PDO (PHP Data Objects) extension.

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

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

// Bind parameter values to the placeholders
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll();