user3427551 user3427551 - 1 month ago 23
JSON Question

How to insert json array into mysql database

Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.

This is my json data.


[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]


This is my Php code.

<?php

$json = file_get_contents('php://input');
$obj = json_decode($data,true);

//Database Connection
require_once 'db.php';

/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");

}
//database connection close
mysql_close($con);

//}
?>


My database connection code.

<?php

//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";

//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>




Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.

Answer
 $json = file_get_contents('php://input');
 $obj = json_decode($json,true);

I think ur passing wrong variable. you should pass $json in json_decode as above..