传递查询时传递失败

时间:2017-05-23 07:31:23

标签: php jquery ajax

我使用ajax调用将$place变量传递给listplace.php中的查询。 ajax调用在php1.php代码中完美运行,但$place值不会通过查询传递。请帮忙!

listplace.php也可以完美运行,但是当我试图在条件失败时传递$ place。

php1.php代码

<select id="name">
  <option selected disabled>Please select</option>
</select>

<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        $.ajax({
            type: "POST",
            data: {place: '<?= $_GET['place'] ?>'},
            url: 'listplace.php',
            dataType: 'json',
            success: function (json) {
                if (json.option.length) {
                    var $el = $("#name"); 
                    $el.empty(); // remove old options
                    for (var i = 0; i < json.option.length; i++) {
                        $el.append($('<option>',
                            {
                                value: json.option[i],
                                text: json.option[i]
                            }));
                    }
                }else {
                    alert('No data found!');
                }
            }
        });
    </script>
<?php } ?>

listplace.php

<?php
//connect to the mysql
$db = @mysql_connect('localhost', 'root', 'password') or die("Could not connect database");
@mysql_select_db('test', $db) or die("Could not select database");

$place = $_POST['place'];

$sql = @mysql_query("select product_name from products_list where product_name = '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
    $rows[] = $r['product_name'];
}
if (count($rows)) {
    echo json_encode(['option'=> $rows]);
}else {
    echo json_encode(['option'=> false]);
}
?>

2 个答案:

答案 0 :(得分:1)

更改此行

 data: {place: '<?= $_GET['place'] ?>'},

 data: {place: '<?= $_GET["place"] ?>'},

答案 1 :(得分:1)

改进将是开始使用准备好的陈述。这只是Exprator的回答

的补充

这将阻止SQL注入攻击。

$sql_con = new mysqli('localhost', 'root', 'password', 'test');//get connection
    $place = $_POST['place'];//posted variable
    if($stmt = $sql_con->prepare("select product_name from products_list where product_name =?")) {//prepare returns true or false

       $stmt->bind_param("s", $place); //bind the posted variable
       $stmt->execute(); //execute query
       $stmt->bind_result($product_name);//bind the result from query securely

        $rows = array();//create result array
       while ($stmt->fetch()) {//start loop
         $rows[] = $product_name;//grab everything in array
       }
       if (count($rows)) {//check for number
            echo json_encode(['option'=> $rows]);
        } else {
            echo json_encode(['option'=> false]);
        }