Im getting json data from another server and need thouse data to be saved on mysql.I tryed this code but theres a problem when i run this code i get : Illegal string offset for each VALUES. I hope I made things clear if there's anything I didn't explain please do tell.
<?php
require('db.php');
$url = 'xxxxx';
$data =json_encode(array('xxx' => 'xxxx',
'xxxx' => 'xxxxx',
'xxxx' =>'xxxx',
'xxxx' =>'xxxx',
'xxxx' =>'xxxx')
);
$options = array(
'http' => array(
'header' => "Content-type: application/json",
'method' => 'POST',
'content' => $data
)
);
$context= stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { }
echo $result ;
foreach ((array)$result as $row) {
$table="INSERT INTO table_name(xxx,xxx,xx,xxx,xx,xxx,xxx,xxxx,xxx)
VALUES('".$row["xxxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxxx"]."')";
if ($conn->query($table ) === TRUE) {
echo "Record added Successfully<br>";
}
else
{
echo "Error: " . $insert_value . "<br>" . $con->error;
}
}
?>
There should be else
statement as well with if
conditions, in case there are results. And the results should be parsed in else
.
The code should be :
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "Error in fetching records.";
} else {
echo $result;
$rows = (array) $result;
foreach ($rows as $row) {
$table = "INSERT INTO table_name(xxx,xxx,xx,xxx,xx,xxx,xxx,xxxx,xxx)
VALUES('" . $row["xxxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxxx"] . "')";
if ($conn->query($table) === TRUE) {
echo "Record added Successfully<br>";
} else {
echo "Error: " . $insert_value . "<br>" . $con->error;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.