2013-04-10 175 views
1

我希望查詢最初返回c_id> 0的所有記錄,然後根據通過文本框提供的後續條件進行過濾。但是,在第一次訪問頁面時,我沒有收到任何記錄。下面是代碼:SQL查詢失敗

$ctitle = mysql_real_escape_string($_POST['ctitle']); 
$csubject = mysql_real_escape_string($_POST['csubject']); 
$creference = mysql_real_escape_string($_POST['creference']); 
$cobjecttype = mysql_real_escape_string($_POST['cobjecttype']); 
$cmaterial = mysql_real_escape_string($_POST['cmaterial']); 
$ctechnic = mysql_real_escape_string($_POST['ctechnic']); 
$cartist = mysql_real_escape_string($_POST['cartist']); 
$csource = mysql_real_escape_string($_POST['csource']); 

    $sql = "SELECT * FROM collections WHERE (
    c_id>0 AND 
    `ctitle` LIKE '{$ctitle}' AND 
    `csubject` LIKE '{$csubject}' AND 
    `creference` LIKE '{$creference}' AND 
    `cobjecttype` LIKE '{$cobjecttype}' AND 
    `cmaterial` LIKE '{$cmaterial}' AND 
    `ctechnic` LIKE '{$ctechnic}' AND 
    `csource` LIKE '{$csource}' AND 
    `cartist` LIKE '{$cartist}' 
    )ORDER BY c_id DESC"; 

當我附和查詢我得到如下印刷代替:

request "Could not execute SQL query" SELECT * FROM collections WHERE (c_id>0 AND `ctitle` LIKE '' AND `csubject` LIKE '' AND `creference` LIKE '' AND `cobjecttype` LIKE '' AND `cmaterial` LIKE '' AND `ctechnic` LIKE '' AND `csource` LIKE '' AND `cartist` LIKE '')ORDER BY c_id DESC 

哪裏應該何去何從?

回答

0

將一個空間)ORDER BY

+0

嗨,我按照你的建議,但仍然是相同的錯誤。我也刪除了一些條件,只保留:$ sql =「SELECT * FROM collections WHERE c_id> 0 ORDER BY c_id DESC」;並返回所有記錄。但我需要這些標準才能工作。 – 2013-04-10 07:16:53

+0

空間也是我能發現的唯一錯誤......你究竟得到了什麼錯誤? – UrGuardian4ngel 2013-07-17 23:53:49

0

之間不需要四處拖where子句元素的括號。

+0

您正在使用哪個數據庫? – SteveP 2013-04-10 06:41:06

+0

嗨,我正在使用MySQL。 – 2013-04-10 07:05:20

0

好吧...我想我明白了...嘗試更換LIKE'LIKE '%'

LIKE'將無法​​工作,因爲那隻能說明空列。通過添加通配符(%)它將顯示匹配所有行的所有行。但它可能是一個更好,更乾淨的解決方案,可以完全動態地構建查詢,省略空WHERE條件。

+0

我有太多的問題需要解決。現在它按預期工作。感謝大家的幫助。 – 2014-10-07 10:33:03