0

数据库

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();
4

1 回答 1

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);
于 2012-07-25T12:56:47.037 回答