What are the potential pitfalls of directly concatenating variables in SQL queries in PHP?

Directly concatenating variables in SQL queries in PHP can lead to SQL injection vulnerabilities. To prevent this, you should use prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, making it impossible for malicious input to alter the query structure.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=myDB", $username, $password);

// Prepare a SQL statement 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', $username);

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

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