AutoSuggest使用PHP / MySQL&阿贾克斯

时间:2011-06-25 04:04:59

标签: php mysql ajax autosuggest

我已经使用PHP / MySQL和Ajax创建了一个自动提示,但当我点击搜索建议时带有('),它不会填满搜索框,但其他一切都会填满。例如,我无法点击“只是无法获得足够”的搜索结果。但我可以点击“只是不能得到足够的”。你们能告诉我为什么吗? 感谢

代码:

<?php
    include('conn2.php');
    $str = strtolower($_GET['content']);         
    if(strlen($str))
    {
        $sel = mysql_query("SELECT DISTINCT title FROM Music WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
        if(mysql_num_rows($sel))
        {
            echo "<table border =\"0\" width=\"100%\">\n";
            if(mysql_num_rows($sel))
            {
                echo "<script language=\"javascript\">box('1');</script>";
                while($row = mysql_fetch_array($sel))
                {
                    $country = str_ireplace($str,"<b>".$str."</b>",($row['title']));
                    echo "<tr id=\"word".$row['title']."\" onmouseover=\"highlight(1,'".$row['title']."');\" onmouseout=\"highlight(0,'".$row['title']."');\" onClick=\"display('".$row['title']."');\" >\n<td>".$country."</td>\n</tr>\n";
                }
            }
            echo "</table>";
        }
    }
    else
    {
        echo "<script language=\"javascript\">box('0');</script>";
    }
?>

2 个答案:

答案 0 :(得分:0)

$str = htmlentities(strtolower($_GET['content'])); 

此外,如果您使用新的PHP版本,则可以使用新的filter_input函数来阻止SQL注入。

供参考: http://php.net/manual/en/function.filter-input.php

答案 1 :(得分:0)

我认为问题可能是搜索结果中的单引号与下面的HTML行中的单引号冲突,后者使用单引号将参数括在鼠标悬停/结束/单击的函数调用上

echo "<tr 
id=\"word" . $row['title'] . "\" 
onmouseover=\"highlight(1,'" . $row['title'] . "');\" 
onmouseout=\"highlight(0,'" . $row['title'] . "');\" 
onClick=\"display('" . $row['title'] . "');\" >\n
    <td>" . $country . "</td>\n
</tr>\n";

正如您将看到的,highlight()和display()函数都将title参数包含在单引号中,标题中的单引号可能与它们冲突,从而破坏了HTML。尝试在$ row ['title']中转义单引号,然后就可以了。

希望这有帮助!