How can you prevent SQL injection attacks when passing values in PHP?

To prevent SQL injection attacks when passing values in PHP, you should always use prepared statements with parameterized queries. This approach separates SQL code from user input, making it impossible for attackers to inject malicious code into your queries.

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

// Prepare a SQL query with a placeholder for the user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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