数据库
start end
2012-07-21 15:40:00 2012-07-28 21:00:00
2012-07-23 20:00:00 2012-07-27 13:00:00
这是我通过phpMyAdmin运行并返回正确的行
SELECT *
FROM `events`
WHERE "2012-07-25 15:40"
BETWEEN START AND END
但是在我的PHP代码上,我刚刚发布的内容,我无法得到任何结果。 (表格提交的所有数据均100%发布)。我错过了什么?
$question= 'SELECT * FROM events WHERE ';
$hasTime = false;
if(!empty($time)) { // @note better validation here
$hasTime = true;
$question .= 'WHERE time=:time BETWEEN start AND end';
}
$hasCity = false;
if(!empty($city)) { // @note better validation here
$hasCity = true;
$question .= 'AND city=:city ';
}
$hasType = false;
if(!empty($type)) { // @note better validation here
$hasType = true;
$question .= 'AND type=:type';
}
$query = $db->prepare($question);
if($hasTime)
$query->bindValue(":time", $time, PDO::PARAM_INT);
if($hasCity)
$query->bindValue(":city", $city, PDO::PARAM_INT);
if($hasType)
$query->bindValue(":type", $type, PDO::PARAM_INT);
$query->execute();
答案 0 :(得分:3)
$question= 'SELECT * FROM events WHERE ';
$hasTime = false;
if(!empty($time)) { // @note better validation here
$hasTime = true;
$question .= 'WHERE time=:time BETWEEN start AND end';
}
您的查询最终会出现WHERE
两次,这是语法错误。变化
$question .= 'WHERE time=:time BETWEEN start AND end';
到
$question .= 'time=:time BETWEEN start AND end';
修改强>
请改用此代码。这样可以避免在未指定time
时获得的其他潜在语法错误。
// Store where clauses and values in arrays
$values = $where = array();
if (!empty($time)) { // @note better validation here
$where[] = ':time BETWEEN `start` AND `end`';
$values[':time'] = $time;
}
if (!empty($city)) { // @note better validation here
$where[] = '`city` = :city';
$values[':city'] = $city;
}
if (!empty($type)) { // @note better validation here
$where[] = '`type` = :type';
$values[':type'] = $type;
}
// Build query
$question = 'SELECT * FROM `events`';
if (!empty($where)) {
$question .= ' WHERE '.implode(' AND ', $where);
}
$query = $db->prepare($question);
$query->execute($values);