2013-05-01 33 views
0

好吧, 我在一個名爲week-select的頁面上有多個select下拉菜單,它的選擇會通過ajax傳遞到我的php頁面。SQL查詢未正確完成 - 不確定爲什麼

我可以很好地獲取數據,但是當查詢運行時,它不能正確完成。

我有這樣的:

//Deal with Week Array 
    $weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/ 
    $weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/ 

    .../*I deal with other variables here, they work fine*/ 

    if ($weekFilter) { 
     $sql[] = " WK IN (?) "; 
     $sqlarr[] = $weekFilter; 
    } 
    $query = "SELECT * FROM $tableName"; 
    if (!empty($sql)) { 
     $query .= ' WHERE ' . implode(' AND ', $sql); 
    } 
    $stmt = $DBH->prepare($query); 
    $stmt->execute($sqlarr); 
    $finalarray = array(); 
    $count = $stmt->rowCount(); 
    $finalarray['count'] = $count; 
    if ($count > 0) { //Check to make sure there are results 
    while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json 
      $finalarray['rowdata'] = $result; 
     } //end While 
    }else if ($count == 0) { //if there are no results - set the json object to null 
      $emptyResult = array(); 
      $emptyResult = "null"; 
      $finalarray['rowdata'] = $emptyResult; 
    } //end if no results 

如果我只是選擇一個本週,偉大工程,並顯示相應的數據。

如果我選擇多個選項(比如周12,14和15)運行查詢,但只有當我手動輸入SQL查詢,結果收到了進入我所想象這個查詢顯示12周

- 它運行並顯示適當的數據。所以如果我把SELECT * FROM mytablename放在WHERE WK IN(12,14,15)中,它就是我想要的。

我無法弄清楚爲什麼我的查詢在這裏沒有正確執行。 任何想法?

**編輯:我從前面的多個選擇一個字符串使用JavaScript數組傳遞到後端之前。

+0

爲什麼不ü簡單地echo查詢當u做multipe選擇,比你看到的秒的問題...的 – Yordi 2013-05-01 17:44:27

+0

重複[我怎樣才能創建在一份聲明()運算符?](http://stackoverflow.com/questions/15990857/reference-frequently-asked-questions-about-pdo#15991146) – 2013-05-01 17:47:46

回答

1

你得到的與值的查詢可能看起來像這樣在IN單個值:

… WK IN ("12,14,15") … 

要麼使用一個佔位符,每個原子值:

if ($weekFilter) { 
    $values = explode(",", $weekFilter); 
    $sql[] = " WK IN (" . implode(",", array_fill(0, count($values), "?")) . ") "; 
    $sqlarr = array_merge($sqlarr, $values); 
} 

或者使用FIND_IN_SET代替的:

$sql[] = " FIND_IN_SET(WK, ?) "; 
+0

我認爲你在這裏正確的道路 - IN很可能看着一個單一的價值。試圖讓你的示例代碼有效(它現在不適用於我,我仍然在學習)。目前它給了我這個錯誤:「語法錯誤,意外';'在$ sql [] =行中。 這讓我有一個很好的方向。 – Hanny 2013-05-01 17:54:27

+0

@Hanny只有一個'''丟失了。 – Gumbo 2013-05-01 17:55:42

+0

仍然收到一個錯誤:「array_fill()期望剛好3個參數,2中給出...」 但到達那裏:)仍在挖掘 - 我認爲你讓我走上正確的道路。看看我能否做到這一點。 – Hanny 2013-05-01 18:03:44

0

我不認爲你可以將一個數組綁定到單數的?佔位符。通常,您必須輸入與數組中元素數量一樣多的?值。

-1

如果您的HTML是正確的,並且您的周選擇有name="week[]",那麼你會得到一個數組與$_GET['week'];,否則沒有[]它只會給你1值。然後,你正在做一個字符串替換,但它不是一個字符串。相反,試試這個:

$weekFilter = implode(',', $_GET['week']);