简而言之,我试图找出我的foreach声明有什么问题。我一直在努力寻找错误超过一天,而且我已经没时间了。该程序应该解析一个json数组并将其发布到mysqli数据库。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$a = print_r(var_dump($GLOBALS),1);
echo htmlspecialchars($a);
$servername = "#";
$username = "#";
$password = "#";
$dbname = "#";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
echo "Connection Successful : ";
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Read JSON file
$jsondata = file_get_contents('scripts/AUDIT_DIR/report.json');
echo "JSON File Read : ";
// Convert and Loop
$item = json_decode($jsondata, true);
echo "JSON File Decoded : ";
foreach($item as $arr)
{
$id = $arr["id"];
$hostname = $arr["hostname"];
$ip = $arr["ip"];
$package = $arr["package"];
$publisher = $arr["publisher"];
$origin = $arr["origin"];
$version = $arr["version"];
$size = $arr["size"];
$sql = "INSERT INTO testtable(id, hostname, ip, package, publisher, origin, version, size)
VALUES ('10', '$hostname', '$ip', '$package', '$publisher', '$origin', '$version', '$size')";
if (mysqli_query($conn, $sql))
{
echo "New record created successfully : ";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
&GT;
答案 0 :(得分:0)
您json_decode()
的回复可能无效,您可以在var_dump($item);
json_decode()
查看此回复
如果json无法解码或者编码数据比递归限制更深,那么在php json_decode()
中将返回NULL。 http://php.net/manual/en/function.json-decode.php
您需要妥善保护$item === null
这样的情况,并且不要假设您将始终获得foreach()
参数的有效回报。
显示$item = null
时发生错误的示例
https://3v4l.org/oNr8P