将数据从JSON放入MySQL数据库

时间:2013-01-12 16:48:06

标签: php javascript sql-server database json

我对JSON和MySQL数据库有疑问。 我想要的是我可以将JSON文件中的数据加载到我的数据库中的字段中。 我的JSON文件如下所示:

{
    "wijken": {
        "11": {
            "id": "kml_1",
            "fid": "0",
            "wijziging": "Ja",
            "nieuwnr": "11",
            "naam": "Noordoost",
            "wijk": "Kanaaldorpen en -zone",
            "wijknr": "11",
            "objectid": "1",
            "area": "0",
            "len": "0"
        },
        "12": {
            "id": "kml_2",
            "fid": "1",
            "wijziging": "Ja",
            "nieuwnr": "12",
            "naam": "Noordoost",
            "wijk": "Oostakker",
            "wijknr": "12",
            "objectid": "2",
            "area": "0",
            "len": "0"
        }
    }
}

我有一个带有“wijken”表的数据库,其中包含字段:

  

ID / FID / WIJZIGING / NIEUWNR / NAAM / WIJK / WIJKNR / OBJECTID /   AREA / LEN

现在我希望json文件中的所有数据都来自该表。 (php + javascript)

有人可以帮我开始吗? (或者给一些好的搜索术语教程)

提前致谢!

2 个答案:

答案 0 :(得分:4)

首先,您需要从文件系统加载文件

$json_string = file_get_contents('some/path/to/file.json');

然后你可以使用json_decode

将json字符串转换为php数组
$data = json_decode($json_string, true); 

此时,您将能够使用$data['wijken']访问数据以进入 wijken 表。

为了将这些数据插入到mysql数据库中,您需要使用一个php mysql扩展,mysqliPDO

我将使用mysqli作为这个例子:

// first create a connection to your database
$mysqli = new mysqli('localhost', 'user', 'password', 'database_name');

// this insert query defines the table, and columns you want to update
$query = <<<SQL
INSERT INTO wijken ('ID', 'FID', 'WIJZIGING', 'NIEUWNR', 'NAAM', 'WIJK', 'WIJKNR', 'OBJECTID', 'AREA', 'LEN')
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
SQL;

$stmt = $mysqli->prepare($query);

// for each of the 'rows' of data in the json we parsed, we will insert each value
// into it's corresponding column in the database, and we are doing this using prepared
// statements.
foreach ($data['wijken'] as $key => $value) {
    $stmt->bind_param(
        // the types of the data we are about to insert: s = string, i = int
        'sissssiiii', 
        $value['id'],
        $value['fid'],
        $value['wijziging'],
        $value['nieuwnr'],
        $value['naam'],
        $value['wijk'],
        $value['wijknr'],
        $value['objectid'],
        $value['area'],
        $value['len']
    );

    $stmt->execute();
}

$stmt->close();

// close the connection to the database
$mysqli->close();

答案 1 :(得分:1)

这将输出你的json键和值。

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}