使用php将JSON中的数据插入mysql [英] insert data from JSON into mysql using php

查看:102
本文介绍了使用php将JSON中的数据插入mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要插入mysql数据库的JSON.我的JSON是

I have an JSON that I would like to insert into mysql database. My JSON is

{"users": { "bert":6.44, "earnie":0.25, "bigbird":34.45 }}

我在mysql中有一个名为"USERSAMOUNTS"的表,带有两个列.

I have a table in mysql called "USERSAMOUNTS" with two coloumns.

这些列分别称为"USERNAME"和"AMOUNT".

The columns are called "USERNAME" and "AMOUNT".

我正在尝试使用foreach循环和爆破在一个查询中将每个名称插入USERNAME列,将每个金额插入AMOUNT列.我正在使用的代码如下....

I am trying to insert each name into USERNAME column and each amount into AMOUNT column in one query using a foreach loop and implode. The code I am using is as follows....

$array = json_decode($data, true);
$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                                    
$hostname = 'localhost';                 // write the rest of your query
$username = 'usersname';
$password = 'userspassword';
try 
{
    $dbh = new PDO("mysql:host=$hostname;dbname=my_database", $username, $password);
    echo 'Connected to database<br />'; // echo a message saying we have connected 
    $count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES ($values)"); 
    echo $count;// echo the number of affected rows
    $dbh = null;// close the database connection
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

....我的问题是当我运行代码时,我得到的只是消息 Connected to database确认数据库连接.没有插入任何记录,也没有错误消息显示.这里有人可以指出我要去哪里哪里,也许可以给我提示如何修复代码?

....my problem is when I run the code all I get is message Connected to database to confirm database connection. No records are inserted and no error messages are shown. Can anyone here point out where I am going wrong and maybe give me a hint as to how to fix the code?

推荐答案

更改代码:

$array = json_decode($data, true);
$rows = array();                                   
foreach($array['users'] as $key => $value)                         
    $rows[] = "('" . $key . "', '" . $value . "')"; 

$values = implode(",", $rows);

这篇关于使用php将JSON中的数据插入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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