Sora Sora - 5 months ago 11
PHP Question

get json array in php with database connection

require "conn.php";
$mysql_qry = "SELECT u.* FROM friends f , users u WHERE u.ID = f.FriendID and f.UserID =$ID";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$arr.= array("user" => array(array("ID"=>$row["ID"],"Name"=>$row["Name"],"Email"=>$row["Email"],"Password"=>$row["Password"],"Image"=>$row["Image"],"Profession"=>$row["Profession"],"status" => "1","call" => "login")));

}
echo json_encode($arr);
}


I am trying to concatenate my result from database to get a json array like this :

{
"user":[
{"ID":"1", "message":"Response code : 200"}
{"ID":"2", "message":"Response code : 200"}
{"ID":"3", "message":"Response code : 200"}
{"ID":"4", "message":"Response code : 200"}
{"ID":"5", "message":"Response code : 200"}
]
}


A list of users return by the query

Answer

Proper code is:

$arr = array('user' => array());
if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        $arr['user'][] = array( 
            "ID" => $row["ID"],
            "Name" => $row["Name"],
            "Email" => $row["Email"],
            "Password" => $row["Password"],
            "Image" => $row["Image"],
            "Profession" => $row["Profession"],
            "status" => "1",
            "call" => "login"
        );
    }
}
echo json_encode($arr);