I'm trying to save some json data that gets generated randomly . It can have 6 keys or just 3 keys as shown below.
Array sample:
sample 1:
{
"report": {
"a-key": "a-value",
"b-key": "b-value",
"c-key": "c-value",
"d-key": "d-value",
"e-key": "e-value",
"f-key": "f-value",
}
}
Sample 2:
{
"report": {
"a-key": "a-value",
"c-key": "c-value",
"f-key": "f-value",
}
}
Database Table name : plogs
columns: id,logdate, logtime, a, b, c, d, e,
id is unique key that auto increments
Below is the Php code i tried to use. I was able to successfully generate a text file for each json input without any errors.however I'm not able to save the values to the database. Can you please let me know where im making a mistake. P.S Part of the code i got it off some tutorials
<?php
// Send `204 No Content` status code.
http_response_code(204);
// Get the raw POST data.
$data = file_get_contents('php://input');
$newfilename = date('Y-m-d-H-i-s') . ".txt";
file_put_contents($newfilename, $data);
// a new json file with one of the 2 sample arrays
$date1 = date('Y-m-d');
$time1 = date('H:i:s');
$b = NULL;
$d = NULL;
$f = NULL;
$connect = mysqli_connect("localhost", "dbuser", "dbpassword", "dbname") or die ("error"); //Connect PHP to MySQL Database
$query = '';
$array = json_decode($data, true); //Convert JSON String into PHP Array
function array_keys_exist(array $array, $keys)
{
$count = 0;
if (!is_array($keys)) {
$keys = func_get_args();
array_shift($keys);
}
foreach ($keys as $key) {
if (isset($array[$key]) || array_key_exists($key, $array)) {
$count++;
}
}
return count($keys) === $count;
}
foreach ($array as $row) //Extract the Array Values by using Foreach Loop
{
if (array_keys_exist($array, 'b-key', 'd-key', 'f-key'))
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $row["b-key"] . "', '" . $row["c-key"] . "', '" . $row["d-key"] . "', '" . $row["e-key"] . "', '" . $row["f-key"] . "' ); ";
} else
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $s1 . "', '" . $row["c-key"] . "', '" . $s2 . "', '" . $row["e-key"] . "', '" . $s1 . "'); ";
}
}
mysqli_multi_query($connect, $query);
mysqli_close($connect);