【问题标题】:How to insert json array into mysql database如何将json数组插入mysql数据库
【发布时间】:2014-04-26 17:50:40
【问题描述】:

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

这是我的 json 数据。

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

这是我的 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);

   //}
   ?>

我的数据库连接代码。

   <?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 作为服务器端脚本请告诉我如何解决这个问题。

【问题讨论】:

  • 也向我们展示db.php的内容。
  • 您的代码看起来不错,即解析 JSON 并插入查询我想它与连接和数据库选择有关。在查询后使用 mysql_error() 看看发生了什么。
  • 我认为您的连接有问题。正如 Amit 所说,显示您的 db.php 代码
  • 使用error_reporting(E_ALL);
  • @amit 在我的问题中更新了我的数据库连接代码,请检查一下

标签: php mysql arrays json


【解决方案1】:

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

$obj = json_decode($json,true);

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

【讨论】:

  • 好收获!!即使我在本地尝试了他的代码,但我在检查它时它是正确的,所以完全错过了他使用错误的变量名!
【解决方案2】:
 $json = file_get_contents('php://input');
 $obj = json_decode($json,true);

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

【讨论】:

    【解决方案3】:
    $string=mysql_real_escape_string($json);
    

    【讨论】:

    • 你能进一步解释你的代码吗?它有什么作用,是什么让您认为它可以解决问题?
    【解决方案4】:

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

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

    【讨论】:

    • 与这里的其他两个答案相比,这提供了什么?
    【解决方案5】:
    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."));
            }
        }
    

    【讨论】:

    • 你能进一步解释你的代码吗?它如何在数据库中插入任何东西?
    • @NicoHaase 查看编辑后的代码。数据库连接文件在另一个文件夹中
    • 我认为没有这些附加文件,任何人都无法使用您的代码。而且我没有要求您提供更多代码,而是提供解释 - 这就是让其他人能够从您的答案中学习的原因
    • 此答案中 90%-100% 的代码与问题无关。任何可能相关的内容似乎都隐藏在此处未显示的其他文件中。可能你没有真正理解问题的重点。
    【解决方案6】:

    很简单,您可以插入 json 数据类型,如下所示。参考链接:click here for more details

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

    【讨论】:

      猜你喜欢
      • 2014-04-26
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      相关资源
      最近更新 更多