【问题标题】:How to import multiple json file into mysql database at same time?如何同时导入多个json文件到mysql数据库?
【发布时间】:2023-01-08 20:48:11
【问题描述】:

我有一个数据库,其中包含大约 10 列。每列应该从单独的 json 文件中获取值。我怎么能同时做到这一点?

例如 :

column1 ------ file1.json
column2 ------ file2.json
column3 ------ file3.json
column4 ------ file4.json

我的 PHP 代码是这样的:

<?php


    //connect to mysql db
    $con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
    //connect to the employee database
    mysql_select_db("employee", $con);

    //read the json file contents
    $jsondata = file_get_contents('file1.json');
    
    //convert json object to php associative array
    $data = json_decode($jsondata, true);
    
    //get the employee details
    $firstcolumn = $data['sample-column'];
  

    
    //insert into mysql table
    $sql = "INSERT INTO tbl_emp(sample-column, )
    VALUES('$id', ')";
    if(!mysql_query($sql,$con))
    {
        die('Error : ' . mysql_error());
    }
?>

我没有任何结果

【问题讨论】:

  • 停止使用过时/删除的mysql_* API 使用mysqli_*PDO。如果mysqli_* forks 你,看起来你也使用了一个非常旧的 php 版本。你应该升级它
  • 你问的是非常基本的sql。 insert into (col1,col2, ...) values (value1, value2..)

标签: php mysql json


【解决方案1】:

您可以使用循环读取每个文件并将数据插入数据库。以下是如何使用 PHP 完成此操作的示例:

<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);

//Loop through the files
$files = array('file1.json', 'file2.json', 'file3.json', 'file4.json');
foreach($files as $file) {
//read the json file contents
$jsondata = file_get_contents($file);

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

//get the employee details
$columnData = $data['sample-column'];

//insert into mysql table
$sql = "INSERT INTO tbl_emp(sample-column) VALUES('$columnData')";
if(!mysql_query($sql,$con)) {
    die('Error : ' . mysql_error());
 }
}
?>

我希望这个答案有所帮助。

【讨论】:

  • 没错,但在(插入 mysql 表)部分,我如何添加多列?
猜你喜欢
  • 2012-01-22
  • 2012-02-18
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 2017-12-19
相关资源
最近更新 更多