【发布时间】:2017-04-23 16:27:56
【问题描述】:
我正在使用 ajax 将数据发送到查询 mysql 并返回结果的 php 页面。我的页面中有一个保存 dept 值的变量。但是,如果我 var_dump($_POST) 我看到 var 是一个数组。
如果我在查询中手动输入一个值,则会返回数据。但是,只是不使用我的 $dept var。
如何解码此数组以使该变量可用于我的查询。谢谢
ajax 代码
$.ajax({
url: 'deptdata.php',
type: "POST",
contentType: "application/json; charset=utf-8",
data: {dept: depts},
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (data) {
alert('error');
}
});
在萤火虫标签中发布
dept=DEMOBILL
deptdata.php
<?php
$dept = $_POST['dept']; <--- array?
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","sample") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select custref from boxes where department = '".$dept."' and status = 1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row = mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
【问题讨论】:
-
你对mysql注入持开放态度,请查看prepared statements。
-
您似乎没有发送任何 json,也不应该发送。不知道为什么要为它设置
contentType。显示如何定义depts -
只在本地,所以在上线之前不需要安全
-
尝试删除
contentType并返回$dept看看是否符合您的预期。