json文件添加到mysql数据库中,如何从一个JSON数组到mysql数据库中插入数据?

I am trying for some time now to insert data from a JSON array into mysql database using php but what ever I try it is not working.

my array looks like so...

Array

(

[] => -4.0533

[bert] => 2

[earnie] => 0.25

[bigbird] => 0.25

[grouch] => 1.25

)

I am trying to insert this data into mysql database that has a table named "useramounts"

the table contains 2 columns. (username,amount) so that each row contains a username and the associated amount

this is probably very simple for you guys but I have never attempted this before. I have tried to google a solution but to no avail. Can anyone help me?

解决方案

What have you tried?

Try this approach:

Convert JSON to PHP array (json_decode())

Loop through the array, get the key and value for each entry (foreach(){}, array_keys())

Create a single string with an insert and add VALUES() for each row

Execute the query after the loop

$keys = array_keys($array); // get the value of keys

$rows = array(); // create a temporary storage for rows

foreach($keys as $key) { // loop through

$value = $array[$key]; // get corresponding value

$rows[] = "('" . $key . "', '" . $value . "')";

// add a row to the temporary storage

}

$values = implode(",", $rows); // 'glue' your rows into a query

$query = "INSERT INTO ... VALUES " . $values;

// write the rest of your query

... // execute query

As soon as you find a concrete question, feel free to open another post.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值