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 }}
I have a table in mysql called "USERSAMOUNTS" with two coloumns.
The columns are called "USERNAME" and "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();
}
....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?