What are some potential pitfalls when using MySQL queries for price allocation based on weight in PHP?

One potential pitfall when using MySQL queries for price allocation based on weight in PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To solve this issue, use prepared statements with parameterized queries to prevent SQL injection vulnerabilities.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT price FROM products WHERE weight <= ? ORDER BY weight DESC LIMIT 1");
$stmt->bind_param("d", $weight);

// Sanitize user input for weight
$weight = filter_var($_POST['weight'], FILTER_VALIDATE_FLOAT);

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

// Display the price
echo "The price for the weight of $weight is $price";