What are the potential pitfalls of using MySQL queries in PHP for retrieving data based on user input like ZIP codes or city names?

When using user input like ZIP codes or city names in MySQL queries in PHP, it is important to sanitize the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries, which helps prevent malicious SQL code from being injected into the query.

// Assuming $zipCode is the user input ZIP code
$zipCode = $_POST['zip_code'];

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM locations WHERE zip_code = :zipCode");

// Bind the parameter
$stmt->bindParam(':zipCode', $zipCode);

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

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

// Loop through the results and do something with them
foreach($results as $result) {
    // Do something with the data
}

// Close the connection
$pdo = null;