What common mistakes or pitfalls should be avoided when writing SQL queries in PHP scripts?

One common mistake to avoid when writing SQL queries in PHP scripts is using concatenated variables directly in the query string, which can lead to SQL injection vulnerabilities. To prevent this, you should use prepared statements with parameterized queries to securely pass variables to the database.

// Incorrect way using concatenated variables in SQL query
$user_id = $_GET['user_id'];
$sql = "SELECT * FROM users WHERE id = $user_id";

// Correct way using prepared statements with parameterized queries
$user_id = $_GET['user_id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();