我正在努力理解PHP中的引用主要是在执行SQL查询时。我一直在接受 此查询出错。
SELECT Hotels.HotelImage1, Holidays.ID, Hotels.HotelName, Destinations.Name, PriceBands.PriceBand_Cost FROM Holidays
INNER JOIN Hotels ON Holidays.Hotel_ID = Hotels.ID
INNER JOIN PriceBands ON Holidays.PriceBand_ID = PriceBands.ID
INNER JOIN Destinations ON Destinations.ID = Holidays.Destination_ID
WHERE Destinations.ID = ".$dest."AND Hotels.ID =".$hotel;
我正在尝试在查询中使用两个PHP变量。任何帮助都会非常感激。
答案 0 :(得分:0)
您的查询应该是
$query = "SELECT Hotels.HotelImage1, Holidays.ID, Hotels.HotelName, Destinations.Name, PriceBands.PriceBand_Cost FROM Holidays
INNER JOIN Hotels ON Holidays.Hotel_ID = Hotels.ID
INNER JOIN PriceBands ON Holidays.PriceBand_ID = PriceBands.ID
INNER JOIN Destinations ON Destinations.ID = Holidays.Destination_ID
WHERE Destinations.ID = '$dest' AND Hotels.ID = '$hotel'";
由于您使用的是ID,如果它是一个整数字段,则不需要在ID值周围加上引号,您也可以这样做
$query = "SELECT Hotels.HotelImage1, Holidays.ID, Hotels.HotelName, Destinations.Name, PriceBands.PriceBand_Cost FROM Holidays
INNER JOIN Hotels ON Holidays.Hotel_ID = Hotels.ID
INNER JOIN PriceBands ON Holidays.PriceBand_ID = PriceBands.ID
INNER JOIN Destinations ON Destinations.ID = Holidays.Destination_ID
WHERE Destinations.ID = $dest AND Hotels.ID = $hotel";
更新:
您需要转义查询输入。您可以使用两种方法来控制用户输入。使用mysqli_real_escape_string或使用prepared statements:
使用mysqli_real_escape:
$dest = $mysqli->real_escape_string($dest);
$hotel = $mysqli->real_escape_string($hotel);
$stmt = "SELECT Hotels.HotelImage1, Holidays.ID, Hotels.HotelName, Destinations.Name, PriceBands.PriceBand_Cost FROM Holidays
INNER JOIN Hotels ON Holidays.Hotel_ID = Hotels.ID
INNER JOIN PriceBands ON Holidays.PriceBand_ID = PriceBands.ID
INNER JOIN Destinations ON Destinations.ID = Holidays.Destination_ID
WHERE Destinations.ID = '$dest' AND Hotels.ID = '$hotel'";
使用准备好的声明:
$stmt = $mysqli->prepare("SELECT Hotels.HotelImage1, Holidays.ID, Hotels.HotelName, Destinations.Name, PriceBands.PriceBand_Cost FROM Holidays
INNER JOIN Hotels ON Holidays.Hotel_ID = Hotels.ID
INNER JOIN PriceBands ON Holidays.PriceBand_ID = PriceBands.ID
INNER JOIN Destinations ON Destinations.ID = Holidays.Destination_ID
WHERE Destinations.ID = ? AND Hotels.ID = ?");
/* Bind parameters. Types: s = string, i = integer, d = double, b = blob */
$stmt->bind_param("ii", $dest, $hotel);
答案 1 :(得分:0)
尝试将最后一个字符串更改为
WHERE Destinations.ID = '".$dest."' AND Hotels.ID ='".$hotel."'";
始终显示sql错误。这是有帮助的
答案 2 :(得分:0)
SQL(大多数风格,无论如何)要求字符串由单引号分隔。您必须在查询中构建它。另外,不要打扰连接变量,因为PHP能够在字符串中找到变量。
答案 3 :(得分:0)
不要以这种方式构建SQL查询。请改用预备语句。它的参数绑定避免了与数据类型,SQL注入攻击和任何安全性相关的任何问题。
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php