2011-11-01 75 views
1

我有這個MySQL查詢使用PHP和第一部分工作正常,但第二部分在網站上有搜索功能根本無法得到它可以正常搜索。 下面是詳細的代碼:搜索功能不工作在我的PHP MySQL查詢

<? 
$qry = " 
SELECT bidprice,timelive,match_title, 
CASE 
WHEN game.result LIKE '' THEN 'PENDING' 
WHEN game.result LIKE 1 THEN 'WON' 
END AS result 
FROM game 
ORDER BY timelive DESC 
"; 
$searchText = ""; 
if($_REQUEST['search_text']!=""){ 
    $searchText = $_REQUEST['search_text']; 
$qry .=" WHERE game.bidprice LIKE '%$searchText%' OR game.timelive LIKE '%$searchText%'"; 
} 

//for pagination 
$starting=0; 
$recpage = 10;//number of records per page 

$obj = new pagination_class($qry,$starting,$recpage);  
$result = $obj->result; 

?> 

所以從正在考慮搜索我的「遊戲」表上面的代碼這部分代碼是不工作:

$searchText = ""; 
if($_REQUEST['search_text']!=""){ 
    $searchText = $_REQUEST['search_text']; 
$qry .=" WHERE game.bidprice LIKE '%$searchText%' OR game.timelive LIKE '%$searchText%'"; 

在我的網頁我收到此錯誤時開放此頁面並嘗試搜索詞「足球」::

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'game.bidprice like '%football%' OR game.timelive like '%football%' at line 9 

把一些簡單的SELECT語句像時,該搜索功能工作正常SELECT * FROM遊戲 但做與CASE那些更復雜的選擇查詢時,當語句,我需要它不能正常工作...

請幫我正確的搜索功能正確的代碼

+1

您的代碼易受SQL注入攻擊。請使用'$ searchText = mysql_real_escape_string($ _ REQUEST ['search_text']);' –

回答

5

的問題是, ORDER BY後面不能有WHERE子句。您的查詢目前看起來是這樣的:

SELECT bidprice,timelive,match_title, 
CASE 
WHEN game.result LIKE '' THEN 'PENDING' 
WHEN game.result LIKE 1 THEN 'WON' 
END AS finalization 
FROM game 
ORDER BY timelive DESC WHERE game.bidprice LIKE '%football%' OR game.timelive LIKE '%football%' 
         ^^^^^^^ error 

但你需要它看起來像這樣:

SELECT 
    bidprice, 
    timelive, 
    match_title, 
    CASE 
     WHEN game.result LIKE '' THEN 'PENDING' 
     WHEN game.result LIKE 1 THEN 'WON' 
    END AS finalization 
FROM game 
WHERE game.bidprice LIKE '%football%' OR game.timelive LIKE '%football%' 
ORDER BY timelive DESC 

你應該在你的PHP腳本添加ORDER BY事後。試試這樣的:

$qry = " 
SELECT bidprice,timelive,match_title, 
CASE 
WHEN game.result LIKE '' THEN 'PENDING' 
WHEN game.result LIKE 1 THEN 'WON' 
END AS result 
FROM game 
"; 

$searchText = ""; 
if ($_REQUEST['search_text']!="") 
{ 
    $searchText = mysql_real_escape_string($_REQUEST['search_text']); 
    $qry .= " WHERE game.bidprice LIKE '%$searchText%' " . 
      " OR game.timelive LIKE '%$searchText%'"; 
} 

$qry .= " ORDER BY timelive DESC"; 
+0

這對我來說非常合適!非常感謝! – Ivy

3

你有幾個錯誤。

第一個:你把WHEREORDER BY

:只使用$searchText = $_REQUEST['search_text'];您可以收到SQL注入。

+0

+1用於指出SQL注入。 –

+0

感謝您在此注意到我作爲初學者,所以沒有意識到這一點。我看到馬克·拜爾斯也在上面的完整代碼中編輯了這個:) – Ivy