返回数组作为JSON友好输出获取

时间:2016-09-04 14:13:42

标签: php sql json

我正在编写一个PHP文件,以便在计算检索到的记录数之前,选择符合标准的表中的所有记录。

我想做的是: 假设它检索了5条记录,我希望PHP文件只返回[{“count”:5}]

有人可以提出一种方法让文件返回上面的内容吗?

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "userid", "password", "dbname");

$admin_no = $_GET['admin_no'];

$result = $conn->query("Select lecturer_id,admin_no,message,date_time_sent,sender from chat where lecturer_id = 'shizukakudo' and admin_no = '". $admin_no ."'");

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
	if ($outp != "[") {$outp .= ",";}
	$outp .= '{"lecturer_id":"'  . $rs["lecturer_id"] . '",';
	$outp .= '"admin_no":"' . $rs["admin_no"] . '",';                 $outp .= '"message":"' . str_replace('"','',$rs["message"]) . '",'; 
	$outp .= '"date_time_sent":"' . $rs["date_time_sent"] . '",';
	$outp .= '"sender":"' . $rs["sender"] . '"}';
}
$outp .="]";

$conn->close();



echo($outp.length);
?>

2 个答案:

答案 0 :(得分:0)

  

我要做的是:假设它检索了5条记录,我希望PHP文件只返回[{"count":5}]

如果这是您的要求,那么使用while循环就没有意义了。执行查询后,只需执行以下操作:

// your code

$result = $conn->query("Select lecturer_id,admin_no,message,date_time_sent,sender from chat where lecturer_id = 'shizukakudo' and admin_no = '". $admin_no ."'");

$outp = array();
$outp[]['count'] = $result->num_rows;
echo json_encode($outp);

旁注:了解prepared statements因为您的查询现在容易受到SQL注入的影响。另请参阅how you can prevent SQL injection in PHP

答案 1 :(得分:0)

像这样使用json_encode()

    <?php
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");

        $conn       = new mysqli("localhost", "userid", "password", "dbname");  
        $admin_no   = $_GET['admin_no'];    
        $result     = $conn->query("Select lecturer_id,admin_no,message,date_time_sent,sender from chat where lecturer_id = 'shizukakudo' and admin_no = '". $admin_no ."'");
        $data       = $result->fetch_array(MYSQLI_ASSOC);

        $arrData    = [
            "count" => count($data)
        ]; 
        $json       = json_encode($arrData);


    ?>