Php 将JSON数据输入MySQL
我正在尝试获取JSON数据并将其输入到我的数据库中 以下是我当前的代码:Php 将JSON数据输入MySQL,php,mysql,sql,json,Php,Mysql,Sql,Json,我正在尝试获取JSON数据并将其输入到我的数据库中 以下是我当前的代码: while($row= mysqli_fetch_assoc($query)){ $id = $row["id"]; $domain = $row["domain"]; $time = date('Y-m-d H:i:s'); $ch = curl_init(); $url = "https://www.example.com/"; curl_setopt($ch, CUR
while($row= mysqli_fetch_assoc($query)){
$id = $row["id"];
$domain = $row["domain"];
$time = date('Y-m-d H:i:s');
$ch = curl_init();
$url = "https://www.example.com/";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "apikey=123&test=$domain");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
print $output;
// CODE SHOULD BE ADDED HERE I THINK
curl_close ($ch);
$sql_to_update = "UPDATE monitoring SET socials='$socials', update_time='$time' WHERE id='$id'";
mysqli_query($conn,$sql_to_update);
}
下面是我得到的JSON结果示例:
{
"resource":"random data",
"tests":100,
"total":250,
"networks":{
"FaceBook":{
"detected":true,
"result":"ignore"
},
"Twitter Inc":{
"detected":false,
"result":"ignore"
},
"MySpace":{
"detected":true,
"result":"ignore"
},
"Pinterest":{
"detected":true,
"result":"ignore"
},
"Instagram":{
"detected":false,
"result":"ignore"
}
}
}
我需要做的就是将检测到的网络设置为true
,并使用变量$socials
将它们插入我的数据库
例如,对于上面列出的JSON示例,我希望在数据库的socials
列中输入以下内容:FaceBook、MySpace、Pinterest
如果没有检测到的网络
设置为true
,则我想在该列中输入NONE FOUND
有人知道如何使用JSON输出将其输入数据库吗?将其作为一个数组,以便更好地处理JSON\u解码($JSON,true)
然后在阵列上执行循环。我希望你知道其余的。你现在该怎么办 检查代码以获取要更新的所需数据:-
输出:-
现在放入您的更新代码,就这样。可能的副本使其成为一个数组,以便更好地处理json\u decode($json,true)
@user10848。很高兴为您提供帮助。
echo '<pre>';
print_r(json_decode($json, true));
echo '</pre>';
stdClass Object
(
[resource] => random data
[tests] => 100
[total] => 250
[networks] => stdClass Object
(
[FaceBook] => stdClass Object
(
[detected] => 1
[result] => ignore
)
[Twitter Inc] => stdClass Object
(
[detected] =>
[result] => ignore
)
[MySpace] => stdClass Object
(
[detected] => 1
[result] => ignore
)
[Pinterest] => stdClass Object
(
[detected] => 1
[result] => ignore
)
[Instagram] => stdClass Object
(
[detected] =>
[result] => ignore
)
)
)
Check the code to get the desired data that you want to update:-
<?php
$link = '{
"resource":"random data",
"tests":100,
"total":250,
"networks":{
"FaceBook":{
"detected":true,
"result":"ignore"
},
"Twitter Inc":{
"detected":false,
"result":"ignore"
},
"MySpace":{
"detected":true,
"result":"ignore"
},
"Pinterest":{
"detected":true,
"result":"ignore"
},
"Instagram":{
"detected":false,
"result":"ignore"
}
}
}'; // suppose json variable is $link
$dataArr = json_decode($link);
echo "<pre/>";print_r($dataArr);// print the variable to see how json data looks when it converted to php array
$socials = '';
foreach($dataArr->networks as $key=>$dataA){
if($dataA->detected == 1){
$socials .= $key.',';
}
}
$socials = trim($socials,',');
echo $socials;
?>