我被告知这段代码很容易受到 SQL 注入的影响。我如何将其更改为安全?我知道使用准备好的语句是最好的,但我还没有找到一种不会破坏它的方法。
<?php
$con = new mysqli("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '" . $_POST[emailaddress] . "'";
$existsResult = mysqli_query($con, $existsQuery);
if ($existsResult->fetch_object()->count > 0) {
header('Location: index2.php?email=exists');
} else {
$sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>