1

Here is the code

$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);

output:

  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) ) 

my question how can i pull individual values and insert them into the database fullname, role and username

hitek
  • 372
  • 1
  • 17
  • 33

3 Answers3

2

By default json_decode turns a JSON object into a PHP object, so you'll need to access it like:

$data->myObject[0]->fullname;

When storing your data in a mysql query:

$query = "INSERT INTO table SET fullname = '{$data->myObject[0]->fullname}'";

If you prefer to use an array instead of an object, you can use:

$data = json_decode($jsonString, true); //notice the 2nd parameter

That way you can access your variables with an array like the two other posters described.

EDIT

You don't really need to use a for loop, you would just set:

$data = json_decode($jsonString, true);
$users = $data['myObject'];

Since you already have a perfectly valid array in $data['myObject'].

Calvin
  • 8,697
  • 7
  • 43
  • 51
  • Is there a better way i can just pull all those values using a for loop and store them into an array – hitek Nov 30 '10 at 20:23
  • i did it this way but i see no new records in the table can you explain what am i doing wrong here? thanks in advance :) $query = "INSERT into $tablename (USER,NETWORKNAME,ROLE) VALUES ('$dataArray[0]['fullname']','$dataArray[0]['username']','$dataArray[0]['role']')"; – hitek Nov 30 '10 at 21:48
  • never mind i got it was missingthe quotes but thanks anyways for your help :) $query = "INSERT into $tablename (USER,NETWORKNAME,ROLE) VALUES ('{$dataArray[0]['fullname']}','{$dataArray[0]['username']}','{$dataArray[0]['role']}')"; – hitek Nov 30 '10 at 21:59
1

to get fullname:

$fullname = $data['myObject'][0]['fullname'];

Same for role/ADMIN

Which you can add to your SQL string to insert into your database.

For an example of an insert into mysql see: http://www.w3schools.com/PHP/php_mysql_insert.asp

wajiw
  • 12,239
  • 17
  • 54
  • 73
1

if you do

$data = JSON_decode($jsonString, true); // just add true

then just use

$name = $data['myObject'][0]['name']; 

and save it

Gabriel Sosa
  • 7,897
  • 4
  • 38
  • 48