实时搜索PHP和MySQL

时间:2017-04-03 20:41:04

标签: php jquery mysql

我正在尝试进行实时搜索。我有一个带有输入值的html页面。输入将采用saleID。然后我有一个连接到MySQL数据库的php文件。我想按销售ID搜索数据库,并根据输入中输入的内容更新html表。然而,我有大部分代码,它说什么都没找到。

首先,我将提供HTML:

<html>
<head>
<title></title>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function ()
{
  load_data();

 function load_data(query)
{
 $.ajax({
 url:"test.php",
 method:"POST",
 data:{query:query},
 success:function(data)
 {
   $('#result').html(data);
 }
});
}

$('#saleID').keyup(function()
{
 var search = $(this).val();
 if(search != '')
 {
   load_data(search);
 }
 else
 {
   load_data();
 }
 });

});
  </script>
  </head>
  <body>
  </body>
  </html>
   <h1>Test</h1>
    <br>
    <br>

    <form>
     <p>Customer ID:</p>
    <input type="text" id="saleID" name="Sale">
    <br>
    <br>
    </form>
    <div id="result"></div>
    </body>
     </html>

然后这是我的test.php文件

 <?php
   header("Cache-Control: post-check=1, pre-check=2");
   header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");

    $choice = $_GET['qu'];
    $output = '';
    $con = mysqli_connect("localhost", "milkiewiczr520", "", "milkiewiczr520") or
    die("Failed to connect to database");

     $sql_command = "SELECT * FROM SALES WHERE CUSTOMERID = " . $choice . ";";

    $result = mysqli_query($con, $sql_command);

   if(mysqli_num_rows($result) > 0)
    {
     $output .= '
     <div>
      <table>
       <tr>
       <th>Sale ID</th>
       <th>Sale Date</th>
       <th>Customer ID</th>
       </tr>
       ';
     while($row = mysqli_fetch_array($result))
     {
       $output .= '
       <tr>
       <td>'.$row["SALEID"].'</td>
       <td>'.$row["SALEDATE"].'</td>
       <td>'.$row["CUSTOMERID"].'</td>
       </tr>
       ';
     }
      echo $output;
     }
    else
    {
       echo 'Data Not Found';
    }

    ?>

我找不到数据。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

当您以POST发送数据时,您将使用$_GET获取数据。通过这种方式获取您的查询:

    $choice = $_POST['query']; // the {query:query} parameter you declared in your ajax call

(而不是:$choice = $_GET['qu'];

顺便说一下,请尝试使用PDO来做更安全的请求。