How can SQL injection be prevented when using user input in SQL queries in PHP?

SQL injection can be prevented by using prepared statements with parameterized queries when interacting with a database in PHP. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database engine can distinguish between code and data, effectively mitigating the risk of SQL injection attacks.

// Establish 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 username = :username");

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

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

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