2013-12-10 111 views
0

我在努力理解PHP中的引號主要是在執行SQL查詢時。我在這個查詢中不斷收到 錯誤。SQL查詢中的多個PHP變量

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變量。任何幫助將不勝感激。

+2

你得到的錯誤是什麼?您可能需要在'。$ dest。「後面添加一個空格,以便與以下AND分開,但這只是一個猜測。 – andrewsi

+2

可能會更安全地使用PDO準備的語句.. http://www.php .net/manual/en/pdo.prepared-statements.php你可以用更多的代碼來更新這個問題嗎? – msturdy

+0

dest和hotel也可能需要引號。 –

回答

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); 
+0

怎麼樣sql注入?我們不知道這些ID來自哪裏.. – msturdy

+0

它適用於我們不需要深入這個大學,我們在下個學期做 – user3087899

0

嘗試改變過去的字符串

WHERE Destinations.ID = '".$dest."' AND Hotels.ID ='".$hotel."'"; 

並始終顯示sql錯誤。這是有用的

0

SQL(大多數口味,反正)要求字符串由單引號分隔。您必須將其構建到您的查詢中。另外,不要打擾連接變量,因爲PHP能夠在字符串內找到變量。