php - 使用 php ajax 在将数据从数据库检索到搜索框时显示结果

标签 php mysql ajax

我将使用简单的 ajax 从数据库中检索数据。作为我的代码,我正在获取输出,但是如果我要使用特定字母“a”进行搜索,它不会显示来自 db 的特定单词,而是显示所有包含字母“a”的名称

            <style>
            #main {
            padding: 10px;
            margin: 100px;
            color: Green;
            width: 365px;
            }
            #display_results {
            color:#222222; padding:5px;
            background: #eeeeee;
            }
            </style>
            <script src="jquery-1.7.1.min.js"></script>
            <script>
            $(document).ready(function(){
            $("#search_results").slideUp();
            $("#button_find").click(function(event){
            event.preventDefault();
            search_ajax_way();
            });
            $("#search_query").keyup(function(event){
            event.preventDefault();
            search_ajax_way();
            });
            });
            function search_ajax_way(){
            $("#search_results").show();
            var search_this=$("#search_query").val();
            $.post("search.php", {searchit : search_this}, function(data){
            $("#display_results").html(data);
            })
            }
            </script>


            <div id="main">
            <form id="searchform" method="post">
            <input type="text" name="search_query" id="search_query" placeholder="Enter Name" size="55">
            </form>
            <div id="display_results"></div>
            </div>

搜索.php

        <?php

    $con=mysql_connect("localhost","root","")or die("unable to connect");
    mysql_select_db("newdb",$con) or die("unable to select database"); 
    $term = strip_tags(($_POST['searchit']));
    $term = mysql_real_escape_string($term); // Attack Prevention
    if($term=="")
    echo "Enter Something to search";
    else{
    $query = mysql_query("select name from userdetail where name like '%{$term}%'");
    $string = '';
    if (mysql_num_rows($query)){
    while($row = mysql_fetch_assoc($query)){
    $string .= "<b><a href='#'>".$row['name']."</a></b> - ";
    //$string .= $row['email']."";
    $string .= "\n";
    }
    }else{
    $string = "No matches found!";
    }
    echo $string;
    }
    ?>

最佳答案

如果您只想要以该词开头的词,您只需要在该词后加上通配符即可。

$query = mysql_query("select name from userdetail where name like '$term%'");

关于php - 使用 php ajax 在将数据从数据库检索到搜索框时显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361759/

相关文章:

php - WordPress:获取数据并排序

php - 追加相关的子选择选项一次

php - 将多维数组的一部分插入mysql数据库

javascript - jQuery timeago 使用 .load 生成的内容

php - 为什么 nl2br() 不工作

javascript - 如何通过php和ajax将html添加到返回的json对象

php - 在 CakePHP 中,int 列作为字符串从 DB 中提取

mysql - 列不会删除唯一约束

ajax - 自定义 AjaxHelper 扩展,合并 AjaxOptions

ajax - Selenium WebDriver-确定元素是否可单击(即,不会被dojo模态灯箱遮盖)