What are the potential pitfalls of directly using user input in a MySQL query in PHP?

Using user input directly in a MySQL query in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access, modify, or delete data. To prevent this, you should always sanitize and validate user input before using it in a query. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input.

// Sanitize and validate user input
$user_input = $_POST['user_input'];
$user_input = filter_var($user_input, FILTER_SANITIZE_STRING);

// Prepare and execute a parameterized query
$stmt = $pdo->prepare("SELECT * FROM table WHERE column = :user_input");
$stmt->bindParam(':user_input', $user_input);
$stmt->execute();

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