2012-07-25 146 views
0

數據庫SELECT查詢失敗使用PDO,工作在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(); 
+0

這段代碼的實際結果SQL查詢是什麼?看起來它在'WHERE'子句中有更多的東西,而不僅僅是你在PHPMyAdmin中測試的東西。此外,它可能有一個或兩個語法錯誤。例如,它看起來像是在加倍'WHERE'關鍵字。我想如果是這樣的話,數據庫會返回一個錯誤。是嗎? – David 2012-07-25 12:57:37

+0

PDO :: PARAM_INT - 應該是字符串不是int – Cups 2012-07-25 13:09:54

回答

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); 
+0

是的,我錯誤地加了第二個WHERE。但即使我刪除了它,我仍然無法獲得任何行。 – EnexoOnoma 2012-07-25 13:00:38

+0

@Kaoukkos請參閱上面的修改。 – DaveRandom 2012-07-25 13:02:10

+0

@Kaoukkos再次編輯。如果它仍然不起作用,請顯示您存儲在'$ time'中的值。 – DaveRandom 2012-07-25 13:06:15