简体   繁体   中英

PHP > Invalid Argument supplied for foreach()

In short, I am trying to figure out what is wrong with my foreach statement. I have been trying to work on finding the error for over a day know and I'm running out of time. This program is supposed to parse a json array and post it up to a mysqli database.

<?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);
    }
}

?>

You likely have an invalid return from your json_decode() you can check this with a var_dump($item); after your json_decode()

In php json_decode() will return NULL if the json cannot be decoded or if the encoded data is deeper than the recursion limit. http://php.net/manual/en/function.json-decode.php

You need to properly guard for such a case that $item === null and not assume you will always get a valid return for your foreach() params.

Example showing your error happens when $item = null https://3v4l.org/oNr8P

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM