搜索功能在我的PHP MySQL查询中不起作用

时间:2011-11-01 17:39:31

标签: php mysql search

我有这个使用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和WHEN语句完成那些更复杂的选择查询时,我需要它不起作用......

请帮助我使用正确的搜索功能代码

2 个答案:

答案 0 :(得分: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";

答案 1 :(得分:3)

你有几个错误。

首先:您将WHERE放在ORDER BY之后。

第二次:只使用$searchText = $_REQUEST['search_text'];即可获得SQL注入。