2017-04-03 97 views
1

我正在尝试进行实时搜索。我有一个输入值的html页面。该输入将采取saleID的。然后我有一个连接到MySQL数据库的PHP文件。我想通过销售ID来搜索数据库,并根据输入中输入的内容更新html表格。然而,我拥有大部分的代码,其中没有任何发现。Live Search PHP和MySQL

首先我要把我的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

您的脚本存在[SQL注入攻击]的风险(http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)看看发生了什么事[小Bobby表](http://bobby-tables.com/)即使[如果你逃避投入,它不安全!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets -around-mysql-real-escape-string)使用[prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)。 –

回答

0

当您以POST形式发送数据时,您正在通过$_GET获取数据。做到这一点的办法让你查询:

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

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

顺便说一句,请尽量使用PDO做更安全的请求。

+0

非常感谢。这是问题。 – Ryan