簡體   English   中英

SELECT查詢使用PDO失敗,可在phpMyAdmin中使用

[英]SELECT query fails using PDO, works in phpMyAdmin

數據庫

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM