Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 $json = file_get_contents('php://input');
 $obj = json_decode($json,true);

I think you are passing the wrong variable. You should pass $json in json_decode as shown above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...