Reputation: 229
I'm pulling records from a database which i'm able to display the data in JSON format the way i want and it works perfectly. The problem here its there's a token i generate on the page which i want to add to the payload that the user gets and this's what i'm getting
{"user_details":[{
"id":"1",
"fname":"xxx",
"lname":"xxx Mensah",
"phone_number":"0000000",
"email":"[email protected]",
"username":"xx",
"password":"xx",
"user_type":"xx"
}],
"token":"xxxxx"}
but i want to get the results like this
[{"user_details":{
"id":"1",
"fname":"xxx",
"lname":"xxx Mensah",
"phone_number":"0000000",
"email":"[email protected]",
"username":"xx",
"password":"xx",
"user_type":"xx"
},
"token":{"xxxxx"}
]
PHP
$token = xxxxx
$row = $conn->query("SELECT * from users where username='".$username."' and password='".$password."'");
$row->setFetchMode(PDO::FETCH_ASSOC);
$userdetails = $row->fetchAll(PDO::FETCH_OBJ);
$results = array(
'user_details' => $userdetails,
'token' => $token
);
echo json_encode(($results));
Upvotes: 0
Views: 207
Reputation: 1148
The [] brackets in a JSON encoded string representation of an object, whilst the {} brackets represents an array. So your user details are showing an object which is an array of key, value pairs. Then you have an array which wraps everything up, the token and user details.
I'd be inclined to try something along the lines of:
$userdetails = $row->fetch(PDO::FETCH_OBJ);
$object = (object) ['userdetails' => $userdetails, 'token' => $token];
echo json_encode($results);
I haven't tested it out, but should be close enough.
Upvotes: 1
Reputation: 1533
It seems that expected json is not valid (the token part), but you can have something similar that looks like this :
[{"user_details":{"id":"1","fname":"xxx","lname":"xxx Mensah","phone_number":"0000000","email":"[email protected]","username":"xx","password":"xx","user_type":"xx"}},{"token":"xxxxx"}]
Code :
$token = xxxxx;
$row = $conn->query("SELECT * from users where username='".$username."' and password='".$password."'");
$row->setFetchMode(PDO::FETCH_ASSOC);
$userdetails = $row->fetch(PDO::FETCH_OBJ);
$results = array(
array(
'user_details' => $userdetails
),
array(
'token' => $token
)
);
echo json_encode($results);
Notice that the result is wrapped inside another array and the token is inside another array.
The fetchAll is replaced by a fetch since you need only one row not all the rows, right ?
This example can help you to know how your data should be structured in order to get the desired result :
<?php
$array = array(
array (
'user_details' =>
array (
'id' => '1',
'fname' => 'xxx',
'lname' => 'xxx Mensah',
'phone_number' => '0000000',
'email' => '[email protected]',
'username' => 'xx',
'password' => 'xx',
'user_type' => 'xx',
),
),
array(
'token' => 'xxxxx'
)
);
echo json_encode($array);
Upvotes: 1
Reputation: 14
did you make a typo? please try this one :
echo json_encode ([$results]);
Upvotes: -1