How can PHP beginners avoid common pitfalls when writing and executing SQL queries in their code?

One common pitfall for PHP beginners when writing SQL queries is not properly sanitizing user input, which can lead to SQL injection attacks. To avoid this, beginners should use prepared statements with parameterized queries to securely pass user input to the database.

// Example of using prepared statements to avoid SQL injection

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

// Prepare a SQL query with a placeholder for 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(PDO::FETCH_ASSOC);

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}