我有一个 JSON,我想将其插入到 mysql 数据库中。我的 JSON 是
{"users": { "bert":6.44, "earnie":0.25, "bigbird":34.45 }}
我在 mysql 中有一个名为“USERSAMOUNTS”的表,有两个列。
这些列称为“USERNAME”和“AMOUNT”。
我正在尝试使用 foreach 循环和内爆将每个名称插入到 USERNAME 列中,并将每个金额插入到一个查询中的 AMOUNT 列中。我使用的代码如下......
$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();
}
....我的问题是当我运行代码时我得到的只是消息
已连接到数据库
以确认数据库连接。不插入任何记录,也不显示任何错误消息。这里有人能指出我哪里出错了,也许可以给我一个关于如何修复代码的提示吗?
最佳答案
更改您的代码:
$array = json_decode($data, true);
$rows = array();
foreach($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
关于php - 使用 php 将 JSON 数据插入 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21780864/