PHP ajax搜索结果弄乱了我的页面

时间:2016-02-29 12:51:11

标签: javascript php jquery html mysql

大家好,我是第一次尝试实时ajax搜索我的网站。我是php的新手,所以对此事的任何帮助都会很棒。我在这里和那里遵循一些教程并尝试使其工作,但每次按下搜索都没有结果。对此事的任何帮助都会很棒。

代码:

<?php
mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
    $search_term = mysql_real_escape_string($_POST['search_term']);
    $query = mysql_query("SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'");
    while(($row = mysql_fetch_assoc($query)) !== false) {
    echo '<li>',$row['ingName'],'</li>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>

    <div class="container">
        <input type="text" class="searchFunction"> <input type = "submit" value ="Search">
        <div class = "dropdown">
        <ul class = "result">
        </ul>
        </div>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('.searchFunction').keyup(function() {
        var search_term = $(this) .attr('value');
        $.post('build.php', {search_term:search_term}, function(data) {
            $('.result').html(data);

            $('.result li').click(function() {
            var result_value = $(this).text();
            $('.searchFunction').attr('value', result_value);
            $('.result').html('');
    });
    });
});
});

    </script>

  </body>
</html>

我再次对此如此陌生,所以我只是想在这个领域建立我的知识。解决这个大问题的任何帮助都会很棒

P.S我知道sql注射:)但现在一步一步x

2 个答案:

答案 0 :(得分:2)

正如已经指出的那样 - 到目前为止使用的方法存在sql注入的风险,因此在致力于使用现已弃用的mysql函数套件之前,您应该明智地阅读并实现{{1当你使用mysqli时,它将为恶意sql注入攻击提供重要保护。

当你的ajax查询被发送到同一页面时(通过发布的代码看起来),一件重要的事情就是退出发送响应的phpafter - 否则你最终会发送整个页面(由于html标签之外的内容也会很糟糕),我怀疑这不是你想要的目标。

对于我未经训练的人来说,ajax函数看起来不错,但由于我不使用jQuery,我可能错了,错过了一些重要的东西。

prepared statements

完整,有效的例子

<?php
    /*
       as the rest of the page doesn't use a db connection, 
       only load the db conn if the page is requested via post
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        /* assign db connection to a variable */
        $conn=mysql_connect("localhost","root","") or die ("could not connect");

        mysql_select_db("reg") or die ("could not find db");

        /* empty() does an implied `isset` */
        if ( !empty( $_POST['search_term'] ) ) {

            $search_term = mysql_real_escape_string( $_POST['search_term'] );

            /* 
               You ought to look at using mysqli ( prepared statements )
               rather than the now deprecated `mysql_*` functions
            */
            $query = mysql_query( "SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'", $conn );

            if( $query ){/* only send response if the query succeeds */
                while( $row = mysql_fetch_assoc( $query ) ) {
                    echo '<li>',$row['ingName'],'</li>';
                }
            }
        }

        mysql_close( $conn );
        /* make sure that the rest of the page is not sent back with the response data */
        exit();
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Gotta have a title!</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        $( document ).ready( function() {
            $('.searchFunction').keyup( function( event ) {
                /* I could not get this to work - I don't know what this is doing as I don't use jQuery */
                /*var search_term = $(this).attr('value');*/


                /* this however does work */
                var el=event.target || event.srcElement;
                var search_term=el.value;

                /* maybe better to search after a few letters have been added? */
                if( search_term.length < 2 )return;

                /* it appears you are posting to the same page */
                $.post( document.location.href, { search_term:search_term }, function( data ) {
                    $('.result').html( data );

                    $('.result li').click( function( event ) {
                        var result_value = $(this).text();

                        $('.searchFunction').attr('value', result_value );
                        $('.result').html('');
                    });
                });
            });
        });
    </script>
  </head>
  <body>
    <div class="container">
        <input type="text" name='search_term' class="searchFunction">
        <input type="submit" value="Search">
        <div class="dropdown">
            <ul class="result"></ul>
        </div>
    </div>
  </body>
</html>

答案 1 :(得分:0)

您可以尝试编写查询而不使用引号,即:

 $query = mysql_query("SELECT ingName FROM ing WHERE ingName   LIKE   '$search_term%'");

您还可以使用'%$search_term%'代替'$search_term'来放松搜索。

另一个可能的问题是mysql_connect()。我正在使用该功能但它对我不起作用所以我决定使用对我有用的mysqli_connect()函数。

更多建议,您不需要==true,您也可以使用 !empty($_POST['search_term'])

一旦你学习了,你也可以尝试PDO功能,这比启动你自己的连接要好得多。 您可以启动这样的PDO连接。

$dbh1 = new PDO('mysql:dbname=dbname;host=127.0.0.1', 'username', 'dbpass');

然后你就可以这样搜索。 - 使用初始化连接。

 $query = "SELECT ingName from ing WHERE ingName LIKE %$search_term%";
 $stmt = $dbh1->prepare($query);
 $stmt->execute();
 $allRows = count($stmt);
 $row = $stmt->fetch(PDO::fetch_assoc);
 foreach($row as $one){
      echo "<li>".$one['ingName']."</li><br>";
 }

干杯!