0

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

2 Answers2

0

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.

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
0

Use json_encode() like so:

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


    ?>
Poiz
  • 7,611
  • 2
  • 15
  • 17
  • This won't work. `count($data)` will give *number of columns* in the table, not the *number of records* in the table. – Rajdeep Paul Sep 04 '16 at 16:28