gpt4 book ai didi

php - 在查询中传递变量时失败

转载 作者:行者123 更新时间:2023-12-01 08:44:05 25 4
gpt4 key购买 nike

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

listplace.php 也可以完美工作,但是当我尝试在 where 条件下传递 $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]);
}
?>

最佳答案

改进将是开始使用准备好的语句。这只是 Exprator 答案的补充

这将防止 SQL 注入(inject)攻击。

$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]);
}

关于php - 在查询中传递变量时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44128455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com