Lai Lai - 1 month ago 5
JSON Question

for loop display undesired result php

The output of the result for the php i created is like this :


{"result":[{"day":"1","count":"0"}]}{"result":[{"day":"2","count":"0"}]}....


but i want the output of the result :


{"result":[{"day":"1","count":"0"},{"day":"2","count":"0"}...]


The following is my php code:

<?php

define('HOST','xx');
define('USER','xx');
define('PASS','xx');
define('DB','xx');


//$month = $_POST['month'];
//$year = $_POST['year'];

$month = 10;
$year=2016;


$con = mysqli_connect(HOST,USER,PASS,DB);

$sql = "select count(entryID) from Entry where
EXTRACT(DAY FROM(entryTime)) = '$day' AND
EXTRACT(MONTH FROM(entryTime)) = '$month' AND
EXTRACT(YEAR FROM(entryTime))= '$year'";

for($day =1 ; $day<31 ; $day++)
{
$day2 = (string)$day;
$res = mysqli_query($con,$sql);

$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('day' =>$day2,
'count' => $row[0]
));

}

}
echo json_encode(array("result"=>$result));


mysqli_close($con);

?>


Asking for help..

Answer

First mistake: You will always get a count of 0 for every query you execute because your string $sql contains an undefined variable $day during its definition.

Second mistake: You are re-declaring $result inside your loop.

Solution:

 $result = array();
 for ($day=1 ; $day<31 ; $day++) {
     $sql = "select count(entryID) from Entry where
         EXTRACT(DAY FROM(entryTime)) = '$day'  AND
         EXTRACT(MONTH FROM(entryTime)) = '$month' AND 
         EXTRACT(YEAR FROM(entryTime))= '$year'";
     $res = mysqli_query($con,$sql);

     $day2 = (string)$day;
     while($row = mysqli_fetch_array($res)) {
         array_push($result,
         array('day' =>$day2,
            'count' => $row[0]
         ));
     }
 }
 echo json_encode(array("result"=>$result));
Comments