查询表

时间:2016-02-16 10:19:02

标签: javascript php mysql ajax

我试图从表中获取值,我面临的问题是无论输入是什么,它都会给我两行的结果。我想将输入ID与表中的ID匹配。这是我试图使用的代码Image of the table is attached文件名与javascript文件链接,其中我有一个click函数,这个javascript(global.js)文件链接到另一个有文本框的文件。 我的主要文件代码在

下面
  <!DOCTYPE html>
<html>
    <head>
        <title>products</title>
    </head>
    <body>
            Item: 
            <input type="text" required id="item">
            <input type="submit" id="item-submit" value="Grab"> 
            <div id="item-data"></div>

            <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script> 
            <script src="js/global.js"></script> 

    </body>
</html>

global.js文件代码

 $(document).ready(function(){
    $('input#item-submit').click(function(){     

        var item = $('input#item').val();    
        if ($.trim(item) != ''){             
            $.post('ajax/name.php',{item:name}, function(data){ 
                $('div#item-data').text(data);  

            });

        }

    })
});

name.php文件代码在

下面
 require '../db/connect.php';

    $sql = "SELECT BarcodeID, shirts, price FROM clothes WHERE BarcodeID = ($_POST['name']) ";

    $result = mysqli_query($con,$sql);
        while($row = mysqli_fetch_array($result)) {
            echo " " . $row["BarcodeID"]. " shirt color:  " . $row["shirts"]. " price: " . $row["price"];
        }
    mysqli_close($con);

2 个答案:

答案 0 :(得分:1)

尝试此查询:

"SELECT BarcodeID, shirts, price FROM clothes WHERE BarcodeID = '{$_POST['name']}'"

为什么要将BarcodeID与名称进行比较?

  

旁注:您的查询不安全。读这个   How can I prevent SQL injection in PHP?

答案 1 :(得分:0)

    $id=$_POST['item']; // your post variable
    $sql = "SELECT BarcodeID, shirts, price FROM clothes WHERE BarcodeID=".$id;

     $result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0)
{
        while($row = mysqli_fetch_array($result)) {
            echo " " . $row["BarcodeID"]. " shirt color:  " . $row["shirts"]. " price: " . $row["price"];
        }
}
else
{
echo "No results found";
}
    mysqli_close($con);