我正在尝试将多个WHERE条件应用于我的查询,如下所示:
$hotel="Hotel Name";
$data1=explode('/',$data1);
$newdata1=mktime(0, 0, 0, $data1[0], $data1[1], $data1[2]);
$newdata1=date("Y-m-d", $newdata1);
$data2=explode('/',$data2);
$newdata2=mktime(0, 0, 0, $data2[0], $data2[1], $data2[2]);
$newdata2=date("Y-m-d", $newdata2);
$filtro=mysql_query("SELECT *
FROM hotels_rates_flat
WHERE htl_name = $hotel AND
given_date>=$newdata1 AND
given_date<=$newdata2
ORDER BY htl_name, city_zone, given_date")
or die(mysql_error());
它返回以下错误:
* 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'do Hotel AND given_date&gt; = 2012-09-01 AND given_date&lt; = 2012-09-05 ORDER BY htl_nam'第1行附近使用正确的语法。*
这真让我烦心,因为我看不出任何明显的错误。
我将不胜感激。
谢谢
答案 0 :(得分:2)
使用PDO来避免SQL注入和错误报告:
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$hotel="Hotel Name";
$data1=explode('/',$data1);
$newdata1=mktime(0, 0, 0, $data1[0], $data1[1], $data1[2]);
$newdata1=date("Y-m-d", $newdata1);
$data2=explode('/',$data2);
$newdata2=mktime(0, 0, 0, $data2[0], $data2[1], $data2[2]);
$newdata2=date("Y-m-d", $newdata2);
try {
$stmt = $db->query("SELECT * FROM `hotels_rates_flat` WHERE `htl_name` = :hotel AND (`given_date` BETWEEN :date1 AND :date2) ORDER BY `htl_name`, `city_zone`, `given_date`");
$stmt->execute(array(':hotel' => $hotel,':date1' => $newdata1,':date2' => $newdata2));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $ex) {
echo $ex->getMessage();
}
// use $results
?>
答案 1 :(得分:1)
问题的根源是引用。您应该使用带有占位符的预准备语句,并让mysql驱动程序弄清楚如何以语法上有效的方式插入值。
您可以使用与mysqli_
类似的mysql_
函数,只需添加一些额外的调用来处理参数。你确实需要一个显式的数据库句柄(我在下面称它为$dbh
;它是从mysqli_connect()
返回的),而不是像mysql_函数那样依赖于隐式的句柄。
$stmt = mysqli_prepare($dbh, 'SELECT * FROM hotels_rates_flat'
. ' WHERE htl_name = ?'
. ' AND given_date BETWEEN ? AND ?'
. ' ORDER BY htl_name, city_zone, given_date');
# the 'sss' means treat all three parameters as (s)trings
mysqli_bind_param($stmt, 'sss', $hotel, $newdata1, $newdata2) or die(mysqli_error($dbh));
$filtro = mysqli_stmt_execute($stmt) or die(mysqli_error($dbh));
或者你可以使用PDO,就像Mihai的回答一样,这有点不同。
答案 2 :(得分:-2)
您需要用单引号包围$hotel
,$newdata1
和$newdata2
。
SELECT * FROM hotels_rates_flat WHERE htl_name = '$hotel' AND ...
您也可以使用BETWEEN
运算符,而不是写出小于&amp;大于:
AND given_date BETWEEN '$newdata1' AND '$newdata2'
您还应该stop using mysql_
个函数。