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';
}

クエリで2回終了し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 に答える