Alireza Ebr Alireza Ebr - 3 months ago 8
PHP Question

PHP JSON Array not returning all rows from my myphpadmin

I´m trying to select all the rows from db but it´s not returning me all the rows. What am I doing wrong below?



$conn=mysql_connect('localhost:3307', 'root', 'usbw');
mysql_select_db('android',$conn);
mysql_set_charset('utf8',$conn);

$response=array();
$result=mysql_query("select * from news");


if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
$temp=array();
$temp["ID"]=$row["ID"];
$temp["TitrNews"]=$row["TitrNews"];
$temp["MiniMatnNews"]=$row["MiniMatnNews"];
$temp["MatnNews"]=$row["MatnNews"];
$temp["TArikh"]=$row["TArikh"];



}

$response["news"]=array();
array_push($response["news"],$temp);

$response["t"]=1;
echo json_encode($response);
}
else {
$response["t"]=0;
$response["massage"]="peyda nashod";
echo json_encode($response);
}





Is there something wrong with this code? My output only displays the last row of my database



{"news":[{"ID":"7","TitrNews":"hi","MiniMatnNews":"hello","MatnNews":":D","TArikh":"1395-09-08"}],"t":1}




Answer

You must declare

$response["news"]=array();

outside (i.e. just before) of the while loop. In fact, you may also don't declare it, as $response = array(); is enough to set our variable (and even dispensable ?).

Now, just before adding our $temp result, we reset the result container,so you only were seeing the last result !

AND :

 array_push($response["news"],$temp);

must be in the wile loop, as we want to add each individual row to the final array.

Here is the way i would have choose :

$conn=mysql_connect('localhost:3307', 'root', 'usbw');
mysql_select_db('android',$conn);
mysql_set_charset('utf8',$conn);

$response=array();
$result=mysql_query("select * from news");

    if(mysql_num_rows($result)>0){
        while($row=mysql_fetch_array($result)){
            $temp=array();
            $temp["ID"]=$row["ID"];
            $temp["TitrNews"]=$row["TitrNews"];
            $temp["MiniMatnNews"]=$row["MiniMatnNews"];
            $temp["MatnNews"]=$row["MatnNews"];
            $temp["TArikh"]=$row["TArikh"];
    // add a new element to the response["temp"] array, containing our result
            $response["news"][]=$temp;    
        }
        $response["t"]=1;
        echo json_encode($response);
    }
    else {
        $response["t"]=0;
        $response["massage"]="peyda nashod";
        echo json_encode($response);
    }