如何将json数组插入到mysql数据库中 [英] How to insert json array into mysql database

查看:196
本文介绍了如何将json数组插入到mysql数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 json 数组插入到我的 MySQL 数据库中.我正在从我的 iphone 传递数据,我已将数据转换为 json 格式,并且我正在使用未插入我的服务器的 url 将数据传递到我的服务器.

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.

这是我的json数据.

This is my json data.

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

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

这是我的 PHP 代码.

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);

   //}
   ?>

我的数据库连接代码.

   <?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');
 ?> 

请告诉我在上面的代码中我做错的地方基本上我不是php开发人员我是移动应用程序开发人员所以我使用php作为服务器端脚本请告诉我如何解决这个问题.

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.

推荐答案

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

我认为您传递了错误的变量.您应该在 json_decode 中传递 $json,如上所示.

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

这篇关于如何将json数组插入到mysql数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆