简体   繁体   English

如何使用php将多个表记录从json导入到mysql

[英]How to import multiple table records from json to mysql using php

I have the json file from multiple table multi records. 我有来自多个表多条记录的json文件。 The json file is created from local mysql database and I also have another online database with same schema. json文件是从本地mysql数据库创建的,我还有另一个具有相同架构的在线数据库。 But every table does not have the same number of fields and same data/value. 但是每个表都没有相同数量的字段和相同的数据/值。 But some of the field names are same for all tables (id, added_on, last_updated). 但是所有表的某些字段名称都是相同的(id,add_on,last_updated)。 I want to import these json file values to the online database by executing a single php file. 我想通过执行单个php文件将这些json文件值导入在线数据库。

The json file as like this: json文件如下所示:

[
    {
        "tableName":"table_Name_1",
        "rows":[
                {   
                    "t1column1":"valuet1row11",
                    "t1column2":"valuet1row12",
                    "t1columnx":"valuet1row1x"
                },
                {   
                    "t1column1":"valuet1row21",
                    "t1column2":"valuet1row21",
                    "t1columnx":"valuet1row2x"  
                },
                {   
                    "t1column1":"valuet1rowx1",
                    "t1column2":"valuet1rowx2",
                    "t1columnx":"valuet1rowxx"  
                }
               ]
    },
        {
        "tableName":"table_Name_2",
        "rows":[
                {   
                    "t2column1":"valuet2row11",
                    "t2column2":"valuet2row12",
                    "t2columnx":"valuet2row1x"
                },
                {   
                    "t2column1":"valuet2row21",
                    "t2column2":"valuet2row22",
                    "t2columnx":"valuet2row2x"  
                },
                {   
                    "t2column1":"valuet2rowx1",
                    "t2column2":"valuet2rowx2",
                    "t2columnx":"valuet2rowxx"
                }
               ]
    },
        {
        "tableName":"table_Name_n",
        "rows":[
                {   
                    "tncolumn1":"valuetnrow11",
                    "tncolumn2":"valuetnrow12",
                    "tncolumnx":"valuetnrow1x"
                },
                {   
                    "tncolumn1":"valuetnrow21",
                    "tncolumn2":"valuetnrow22",
                    "tncolumnx":"valuetnrow2x"  
                },{ 
                    "tncolumn1":"valuetnrowx1",
                    "tncolumn2":"valuetnrowx2",
                    "tncolumnx":"valuetnrowxx"
                }
               ]
    },
]

The following php code is used to import the json file records to a single table in the database. 以下php代码用于将json文件记录导入数据库中的单个表中。 (Here the single_table.json only contains a single table records) (这里的single_table.json仅包含单个表记录)

<?php
    try
    {
        $connect = mysqli_connect("localhost", "fmart", "password", "mart_dbsync");    
        $query = '';
        $table_data = '';
        $filename = "single_table.json";

        $data = file_get_contents($filename);
        $array = json_decode($data, true); 

        foreach($array as $row) 
        {
            $query .= "INSERT INTO purchases(id, invoicenum, supplier, stock_keeper, counter, added_by, is_deleted, description, is_opening_stock, department, added_on, last_updated) VALUES ('".$row["id"]."', '".$row["invoicenum"]."', '".$row["supplier"]."', '".$row["stock_keeper"]."', '".$row["counter"]."', '".$row["added_by"]."', '".$row["is_deleted"]."', '".$row["description"]."', '".$row["is_opening_stock"]."', '".$row["department"]."', '".$row["added_on"]."', '".$row["last_updated"]."') ON DUPLICATE KEY UPDATE invoicenum='".$row["invoicenum"]."', supplier='".$row["supplier"]."', stock_keeper='".$row["stock_keeper"]."', counter='".$row["counter"]."', added_by='".$row["added_by"]."', is_deleted='".$row["is_deleted"]."', description='".$row["description"]."', is_opening_stock='".$row["is_opening_stock"]."', department='".$row["department"]."', added_on='".$row["added_on"]."', last_updated='".$row["last_updated"]."';";
        }

            mysqli_multi_query($connect, $query);  

            echo "<h1>All purchases appended </h1>";
    } 

    catch(Exception $e)
    {   
        echo $e->getMessage();    
    }
?>

In the above php code the table name is hard coded in the INSERT statement. 在上面的php代码中,表名在INSERT语句中进行了硬编码。 But by using the new json (as the json format above) it contains more than 25 tables and the table name should be taken from the json file. 但是通过使用新的json(如上面的json格式),它包含25个以上的表,并且表名应从json文件中获取。

here is the echo'd results: 这是回显的结果:

contacts

Insert query:

INSERT INTO contacts 
(First_Name, Last_Name, Company, Business_Phone, Email_Address)
VALUES
('Dave','Frank','Company1','0115 999999','zvv@zz.com'),
('Dave','Blogs','Company2','0115 888888','zvv@zz.com'),
('David','frank','Company3','0115 777777','zvv@zz.com')

Error: 1
INSERT INTO contacts (First_Name, Last_Name, Company, Business_Phone, Email_Address) VALUES ('Dave','Frank','Company1','0115 999999','zvv@zz.com'), ('Dave','Blogs','Company2','0115 888888','zvv@zz.com'), ('David','frank','Company3','0115 777777','zvv@zz.com')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1contacts_old

Insert query:

INSERT INTO contacts_old 
(First_Name, Last_Name, Company, Business_Phone, Email_Address)
VALUES
('Dave','Frank','Company1','0115 999999','zvv@zz.com'),
('Dave','Blogs','Company2','0115 888888','zvv@zz.com'),
('David','frank','Company3','0115 777777','zvv@zz.com')

Error: 1
INSERT INTO contacts_old (First_Name, Last_Name, Company, Business_Phone, Email_Address) VALUES ('Dave','Frank','Company1','0115 999999','zvv@zz.com'), ('Dave','Blogs','Company2','0115 888888','zvv@zz.com'), ('David','frank','Company3','0115 777777','zvv@zz.com')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

This is just a framework to show the idea of building the query based on the data in the JSON. 这只是一个框架,展示了基于JSON中的数据构建查询的想法。 It would require some tweaking and adjusting based on your actual data and table schemas. 这将需要根据您的实际数据和表模式进行一些调整和调整。

As a refinement, I would also build a single INSERT for each table, with multiple values. 作为改进,我还将为每个表构建一个具有多个值的INSERT。

EDIT 编辑

Changed the code to read and insert all tables in JSON file. 更改了代码以读取所有表并将其插入JSON文件。 Presumes that table names and column names in the JSON file match with the actual tables. 假定JSON文件中的表名和列名与实际表匹配。 It also adds the ON DUPLICATE KEY UPDATE for tables that have an id column. 它还为具有id列的表添加ON DUPLICATE KEY UPDATE。

NOTE: Not tested, may have typos. 注意:未经测试,可能有错别字。

<?php
    try
    {
        $connect = mysqli_connect("localhost", "fmart", "password", "mart_dbsync"); 
        $query = '';
        $table_data = '';
        $filename = "single_table.json";

        $data = file_get_contents($filename);
        $array = json_decode($data, true); 

        foreach($array as $set) 
        {
            $tblName = $set['tableName'];
            if(sizeof($set['rows']) > 0) {
                $query = '';
                $colList = array();
                $valList = array();
                //  Get list of column names
                foreach($set['rows'][0] as $colname => $dataval) {
                    $colList[] = "`".$colName."`";
                }
                $query .= "INSERT INTO `".$tblName."` \n";
                $query .= "(".implode(",",$colList).")\nVALUES\n";
                //  Go through the rows for this table.
                foreach($set['rows'] as $idx => $row) {
                    $colDataA = array();
                    //  Get the data values for this row.
                    foreach($row as $colName => $colData) {
                        $colDataA[] = "'".$colData."'";
                    }
                    $valList[] = "(".implode(",",$colDataA).")";
                }
                //  Add values to the query.
                $query .= implode(",\n",$valList)."\n";
                //  If id column present, add ON DUPLICATE KEY UPDATE clause
                if(in_array("`id`",$colList)) {
                    $query .= "ON DUPLICATE KEY UPDATE\n\tSet ";
                    $tmp = array();
                    foreach($colList as $idx => $colName) {
                        $tmp[] = $colName." = new.".$colname." ";
                    }
                    $query .= implode(",",$tmp)."\n";
                } else {
                    echo "<p><b>`id`</b> column not found. <i>ON DUPLICATE KEY UPDATE</i> clause <b>NOT</b> added.</p>\n";
                    echo "<p>Columns Found:<pre>".print_r($colList,true)."</pre></p>\n";
                }
                echo "<p>Insert query:<pre>$query</pre></p>";
                $r = mysqli_query($connect, $query);  
                echo "<h1>".mysqli_num_rows($r)." Rows appeded in $tblName</h1>";
            } else {
                echo "<p>No rows to insert for $tblName</p>";
            }
        }
    } 

    catch(Exception $e)
    {   
        echo $e->getMessage();  
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM