json数据mysql数据库,将数据从JSON放入MySQL数据库

I have a question about JSON and MySQL Database.

What I want is that I can load the data from a JSON-file into my fields in my database.

My JSON-file looks like this:

{

"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"

}

}

}

And I have a database with a table "wijken" with fields:

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

AREA / LEN

Now I want that all the data from the json-file comes in that table. (php + javascript)

Can someone help me start? (Or give a tutorial of some good search terms maybe)

Thanks in advance!

解决方案

First you need to load the file from the filesystem

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

Then you can turn the json string into a php array using json_decode

$data = json_decode($json_string, true);

At this point you will be able to access the data to go into the wijken table with $data['wijken'].

In order to insert this data into a mysql database, you will need to use one of the php mysql extensions, either mysqli or PDO.

I will use mysqli for this example:

// 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 = <<

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值