Click here to Skip to main content
15,912,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a below json in PHP and want to fetch name and number from it and store it in database

Java
{
	"student": [{
		"Name": "John",
		"Number": "1234567890"
	}, {
		"Name": "Jonny",
		"Number": "0987654321"
	}, {
		"Name": "Tom",
		"Number": "0212365895"
	}]
}


I have tried below code but not able to fetch it:
PHP
<?php 
//http://localhost:8080/sample1/webservice2.php?json={%22UserName%22:1,%22FullName%22:2}
//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);

echo $json;

//Save
$con=mysql_connect("localhost","USERNAME","PASSWORD");
mysql_select_db("DATASASE",$con);

  /* grab the posts from the db */
  //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
  //for($i=0;i<count($obj);$i++){
	mysql_query("INSERT INTO Contact (Name, Number) VALUES ('".$obj->{'student'}{'Name'}."', '".$item->{'Number'}."')");
//}

mysql_close($con);
//
  //$posts = array($json);
  $posts = array(1);
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));

?>
Posted
Updated 6-Dec-15 23:54pm
v2
Comments
Kornfeld Eliyahu Peter 7-Dec-15 6:15am    
'Not able'? Why? there are errors? Did you run it with debugger?
bhavikadb 7-Dec-15 6:35am    
Yes I ran it and its giving me blank values and only one row is inserted with blank values

1 solution

You are accessing the values in a wrong way...
It should be like this
PHP
$name = $obj->student[index]->Name;
$number = $obj->student[index]->Number;
 
Share this answer
 
Comments
bhavikadb 7-Dec-15 6:49am    
Its still giving me blank values
Kornfeld Eliyahu Peter 7-Dec-15 6:55am    
Did you wrote 'index' or replaced it with a number according to the row you handle?
bhavikadb 7-Dec-15 6:55am    
yes I replaced it with a "0"
Kornfeld Eliyahu Peter 7-Dec-15 7:01am    
Check your $json after initializing - maybe it is empty...
bhavikadb 7-Dec-15 7:03am    
I have echo $json in the code that only gives me the Above JSON Structure

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900