php 如何将json数组插入到mysql数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22523575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:05:04  来源:igfitidea点击:

How to insert json array into mysql database

phpmysqlarraysjson

提问by user3427551

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 数组插入到我的 MySQL 数据库中。我正在从我的 iphone 传递数据,我已经将数据转换为 json 格式,并且我正在使用它没有插入我的服务器的 url 将数据传递到我的服务器。

This is my json data.

这是我的json数据。

[{"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"}]

This is my Php code.

这是我的 PHP 代码。

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

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

回答by Amit

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

I think you are passing the wrong variable. You should pass $jsonin json_decodeas shown above.

我认为你传递了错误的变量。你应该通过$jsonjson_decode如上图所示。

回答by web-nomad

There is no such variable as $data. Try

没有这样的变量$data。尝试

$obj = json_decode($json,true);

Rest looks fine. If the error still persists, enable error_reporting.

休息看起来不错。如果错误仍然存​​在,请启用error_reporting

回答by Ocpd Manxoloh

You are missing JSON source file. Create a JSON file then assign it to var data:

您缺少 JSON 源文件。创建一个 JSON 文件,然后将其分配给 var 数据:

<?php

require_once('dbconnect.php');

// reading json file
$json = file_get_contents('userdata.json');

//converting json object to php associative array
$data = json_decode($json, true);

// processing the array of objects
foreach ($data as $user) {
    $firstname = $user['firstname'];
    $lastname = $user['lastname'];
    $gender = $user['firstname'];
    $username = $user['username'];

    // preparing statement for insert query
    $st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');

    // bind variables to insert query params
    mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);

    // executing insert query
    mysqli_stmt_execute($st);
}

?>

回答by Rohit Ghodadra

header("Access-Control-Allow-Origin: http://localhost/rohit/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';

//get Database connection
$database = new Database();
$db = $database->getConnection();

//instantiate product object
$product = new Product($db);

//get posted data
$data = json_decode(file_get_contents("php://input"));

//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;

$name_exists = $product->nameExists();

if($name_exists){

    echo json_encode(
            array(
                "success"=>"0",
                "message" => "Duplicate Record Not Exists."

            )
        );

}   else{

        if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){

                if($product->create()){
                //set response code
                http_response_code(200);

                //display message: Record Inserted
                echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
            }

        }   
        else{

            //set response code
            http_response_code(400);

            //display message: unable to insert record
            echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
        }
    }

回答by SaiSurya

Its simple you can insert json datatype as below. reference link: click here for more details

它很简单,您可以插入 json 数据类型,如下所示。参考链接:点击此处了解更多详情

insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"}, 
{"test":"test"}]',0,'pasds');

回答by MrPostman

$string=mysql_real_escape_string($json);