0

I have database values as JSON. I want to get values assigned to key like "name". How can I get those in PHP?.

<?php

include('db.class.php');

$sql = "select * from users where 1";

$obj = new db();
$stmt = $obj->conn->prepare($sql);
$stmt->execute();

$res = $stmt->fetchAll(PDO::FETCH_ASSOC);

$json = json_encode($res,true);

echo $big = $json->name; // ??? ERROR

my output is

[
    {"id":"1",
    "name":"test1",
    "username":"abc",
    "email":"[email protected]",
    "phone":"333"
    },
    {"id":"2",
    "name":"test2",
    "username":"def",
    "email":"[email protected]",
    "phone":"23232"}
]
4
  • $json is a string, not an object. And there's more than one row in the results, which one are you expecting $json->name to return? Commented Jul 13, 2017 at 9:47
  • Can you post the output of echo '<pre>' . print_r($res, true) . '</pre>'; so we can see what exactly is the structure of returned result Commented Jul 13, 2017 at 9:47
  • Would it not be simpler to do $res[0]['name'] Commented Jul 13, 2017 at 9:50
  • Take a quick dip into The PHP manual for json_encode() and see if parameter 2 has a TRUE option in there! Then you might like to swim over to json_decode() just to say hello Commented Jul 13, 2017 at 9:52

2 Answers 2

2

You don't need to use json_encode(). $res is an array of the results, you can access the names from that.

echo $res[0]['name'];

Note that the elements of $res are associative arrays, not objects, because you use PDO::FETCH_ASSOC.

Sign up to request clarification or add additional context in comments.

1 Comment

Finally some one agree's with me
0

First you decode jason array then fetch the result

$data= json_decode($json);

echo $data[0]->name; 

if you need more information about jason_decode then read manual

2 Comments

$data[0]->name
Would it not be simpler to do $res[0]['name'] and cut out all this unnecesary dancing with JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.