使用 PHP、AJAX 和 jQuery 搜索 MySQL 数据库


Searching MySQL database with PHP, AJAX and jQuery

我正在尝试编写一个非常简单的搜索系统,用户在一个只有大约 50 个条目的小型数据库中搜索产品。我正在尝试使用 jQuery 和 AJAX 将搜索查询发送到外部 PHP 脚本,该脚本执行实际的 MySQL 查询并返回结果列表,然后我可以将其附加到搜索页面。

我的搜索页面有这个:

<form method="get">
   <input type="text" id="searchbox" name="search"/>
   <button class="button" id="searchbutton">Search</button>
</form>

<script type="text/javascript">
    function makeAjaxRequest() {
    $.ajax({
        url: 'search_execute.php',
        type: 'get',
        datatype: 'html',
        data: {search: $('#searchbox').val()},
        success: function(response) {
            alert("Success!");
        }, error : function() {
            alert("Something went wrong!");
       }
    });

});
//capture user clicking button
$('#searchbutton').click(function(){
     makeAjaxRequest();
});
//capture user pressing 'return'
$('form').submit(function(e){
    e.preventDefault();
    makeAjaxRequest();
});      
</script>

当然,在这里我只是使用警报进行调试。

这是我来自外部脚本的 PHP:

<?php
require('connection.php');
if(isset($_GET['search'])) {
    $search = $_GET['search'];
    echo $search;
    $stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE '%' ? '%'");
    $stmt -> execute(array($search));
    $num = $stmt->rowCount();
}
if ($num == 0){
    echo "<p>Sorry, no products matched your search</p>";
} else {
    if ($num == 1){
            echo '<p>We have found 1 product that matches your search terms. Please click the link to visit the product page.</p>';
        } else {
            echo '<p>We have found '.$num.' products that match your search terms. Please click a link to visit the product page.</p>';
        }
        echo '<ul class="products>';
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            echo '<li><h3><a href="product.php?id='.$row['product_id'].'">'.$row['product_name'].'</a></h3></li>';
        }
    echo '</ul>';
}
?>
问题是,它失败了

,而且它默默地失败了。无论哪种方式,我都没有收到警报,控制台或Firebug中也没有错误。PHP 单独工作正常,但是当我使用搜索页面时 - bupkus。

编辑:我已经将事件处理程序移到了makeAjaxRequest函数之外,但仍然没有骰子。

你的 Javascript 代码不正确,你在函数中添加的事件函数makeAjaxRequest,因此它从未被调用过。它应该是

<script type="text/javascript">
$(document).ready(function(){
    function makeAjaxRequest() {
        $.ajax({
            url: 'search_execute.php',
            type: 'get',
            datatype: 'html',
            data: {search: $('#searchbox').val()},
            success: function(response) {
                    alert("Success!");
            }, 
            error : function() {
                    alert("Something went wrong!");
            }
        });
    }
    $('#searchbutton').click(function(){
            makeAjaxRequest();
    });
    $('form').submit(function(e){
            e.preventDefault();
            makeAjaxRequest();
    });
});          

你的括号在 JavaScript 代码中有点奇怪。现在看起来,事件绑定位于 makeAjaxRequest(( 函数中,因此在首次调用函数之前,处理程序永远不会绑定到事件。当然,该函数仅从事件处理程序调用,因此永远不会调用。

要解决此问题,只需将绑定复制粘贴到函数外部即可。

还可以将第一个绑定更改为

$('#searchbutton').click(makeAjaxRequest);

以获得较小的性能提升。

你应该像这样使用你的查询

$q = '%' .$search. '%'
$stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE ?");
$stmt->execute(array($q));
<script type="text/javascript">
$(document).ready(function(){
    var sval = $('#searchbox').val();
    var datastring = "search="+sval;
    $('#searchbutton').click(function(){
        $.ajax({
            url: 'search_execute.php',
            type: 'get',
            datatype: 'html',
            data: datastring,
            success: function(response) {
                alert("Success!");
            }, error : function() {
                alert("Something went wrong!");
           }
        });
    });
});
</script>

在 php 文件更改 sql 中

$stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE '%".$search."%' ");