Lionel Lim Ah Kok Lionel Lim Ah Kok - 2 months ago 6
JSON Question

Return Count of Array Fetched as JSON friendly output

I am coding a PHP file to select all records in a table which matches the criterias, before counting the number of records retrieved.

What I'm trying to do is:
Assuming it retrieves 5 records, I want the PHP file to return only [{"count":5}]

Can someone propose a way to make the file return the above?



<?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);
?>




Answer

What I'm trying to do is: Assuming it retrieves 5 records, I want the PHP file to return only [{"count":5}]

If this is your requirement, then there's no point using that while loop. After executing the query, simply do this:

// 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);

Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.

Comments