javascript:验证db中是否存在输入的数据并返回数据

时间:2016-03-15 03:11:20

标签: javascript php jquery database

我有一张桌子: DB

 city
 -------
 cityID
 cityname
 store

我有一个表单HTML:

<input type="text" class="store">

目标:

我想要javascript,在我进入商店后,(如果输入的值已经在数据库中)显示如下警告:

&#34;已经为以下城市输入了商店:纽约(ID#),波士顿(ID#),斯普林菲尔德(ID#)和#34;

我尝试过使用Json文件:

<?php include ('connectionlink.php');
 $word = $_GET['word'];

$search = "SELECT
            store as value,
            cityID,
            cityname,
            FROM city
            WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
    $row['value']=htmlentities(stripslashes($row['value']));
    $row['cityID']=$row['cityID'];  
    $row['cityname']=$row['cityname'];      
    $row_set[] = $row;
}
echo json_encode($row_set);
?>

和javascript

$(document).ready(function (){

 $('.store').on('change', function(){
    var storeValue = $('.store').val();

    $.post('stores.php',{'word' : storeValue}, function(data) {
          alert("Data: " + data);
    }); 

 });
});

我觉得我几乎就在那里,因为在输入商店后我得到一个未定义索引字错误的警报,然后警报以Json格式显示我表中的所有数据。如果它不仅仅搜索我的单词,而只是返回所有内容,就好了。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

您正在发布帖子请求,因此请使用$_POST

阅读参数
$word = $_POST['word']

还要确保处理sql injection How can I prevent SQL injection in PHP?

答案 1 :(得分:1)

<?php include ('connectionlink.php');
//as you are doing a post request...
 $word = $_POST['word'];

$search = "SELECT
            store as value,
            cityID,
            cityname,
            FROM city
            WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
    $row['value']=htmlentities(stripslashes($row['value']));
    $row['cityID']=$row['cityID'];  
    $row['cityname']=$row['cityname'];      
    $row_set[] = $row;
}
echo json_encode($row_set);
?>