What are common pitfalls when generating MySQL queries dynamically in PHP scripts?

One common pitfall when generating MySQL queries dynamically in PHP scripts is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with bound parameters to ensure that user input is safely handled.

// Example of using prepared statements to dynamically generate a MySQL query in PHP

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

// User input (could come from a form submission, for example)
$user_input = $_POST['user_input'];

// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM my_table WHERE column_name = :user_input");

// Bind the user input to the placeholder
$stmt->bindParam(':user_input', $user_input);

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

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

// Output the results
print_r($results);