如何从一个JSON数组到mysql数据库中插入数据? [英] How do I insert data from a json array into mysql database?

查看:711
本文介绍了如何从一个JSON数组到mysql数据库中插入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一段时间了使用PHP,但什么都我尝试它不工作从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  
)

我想插入这个数据到MySQL数据库有一个表名为useramounts
表中包含2列。 (用户名,金额)使每一行包含一个用户名和相应的金额

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?

推荐答案

你尝试过什么?

试试这个办法:

  • 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.

这篇关于如何从一个JSON数组到mysql数据库中插入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆