我一直在试图弄清楚如何将搜索结果加载到表中,但不管我做什么,我只得到一个结果,而不是数据库中表中的2(样本大小)行。PHP-JQuery-Ajax:如何使用mysql查询结果(json编码数组)的所有结果填充表
这是MySQL代码:
if (isset($_POST['search_value'])) {
$search_value = mysqli_real_escape_string($conn, $_POST['search_value']);
$sql = "SELECT
record_id,
personal_id,
name,
status,
entry_date
FROM sample_db
WHERE EmpID = '".$search_value."'";
$res = mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
$data = array();
while($row = mysqli_fetch_array($res)){
$data = array(
'tb_record_id' => $row['record_id'],
'tb_personal_id' => $row['personal_id'],
'tb_name' => $row['name'],
'tb_status' => $row['status'],
'tb_entry_date' => $row['entry_date'],
);
}
echo json_encode($data);
}
我读过几个例子,其中阵列被构建为$数据[] =阵列(数据放在这里),而不是$数据=阵列(数据去这里),但每当我尝试$ data []时,它都不会返回任何内容,但控制台日志会显示数组中的所有结果。
另外,使用dataType:'json'似乎也不工作。
我迄今试过的唯一方法是给每个<td>
一个ID。
Ajax代码
$.ajax({
type : 'POST',
url : 'search_fetch.php',
data : data,
cache: false,
success : function(response)
{
result = jQuery.parseJSON(response);
$("#list_p_id").append(result.tb_personal_id);
$("#list_name").append(result.tb_name);
$("#list_status").append(result.tb_status);
$("#list_date").append(result.tb_entry_date);
}
});
我怎么能填充所有可用的结果表?
此外,如果有帮助,我打开不使用数组。我只是不知道如何将查询结果发送到ajax响应的另一种方式。
您必须使用'$ data [] = array ...'来获取所有结果。现在你用每一个新的结果覆盖'$ data'。 并将输出('echo jeson_encode($ data)')移到while循环之外。 – Jeff
然后,在js中:您不需要parseJson,我认为已经由jQuery完成了。然后使用'result [0] .tb_personal_id'来获取你的数据。 – Jeff
你的脚本存在[SQL注入攻击]的风险(http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) 看看发生了什么[ Little Bobby Tables](http://bobby-tables.com/)即使 [如果你正在逃避输入,它不安全!](http:// stackoverflow。com/questions/5741187/sql -injection-that-around-mysql-real-escape-string) 使用[prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared- statement.php) – RiggsFolly