Invalid argument supplied for foreach() warning

I want to insert json array data in mysql table. I have written this code.

if (mysqli_connect_errno()){
    $response["success"] = 0;
    $response["message"] = "Database Error!";   
    die(json_encode($response));
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

if(isset($_GET['doctorJson'])){

    $json = $_GET['doctorJson'];

    $array = json_decode($json, true);

    foreach($array as $item){

        $result = mysqli_query($con, "INSERT IGNORE INTO doctor_visit_track (id, doctor_name, doctor_email, date, time) VALUES 
            ('".$item['id']."', '".$item['doctorName']."', '".$item['doctorEmail']."', '".$item['date']."', '".$item['time']."')");

            }

    if($result){
        $response["message"] = "Success";
        echo json_encode($response);
    } else{
        $response["message"] = "Failure";
        echo json_encode($response);
        }
    }

mysqli_close($con);

Above code is working fine when I am using xampp. But when I have uploaded this code to server then same code is giving warning " Invalid argument supplied for foreach()" and not inserting in table. But using in xampp, code is working fine and inserting data successfully. Somebody help me..


Not a complete answer but an observation that your code is vulnerable to SQL injection . Try:

$sql = <<<EOF
INSERT IGNORE INTO 
  doctor_visit_track (id, doctor_name, doctor_email, date, time) VALUES 
  ('?', '?', '?', '?"', '?')")
EOF;

$stmt = mysqli_prepare( $con, $sql);

foreach ($array as $item){
    mysqli_stmt_bind_param( $stmt, "sssss",
      $item['id'], $item['doctorName'], $item['doctorEmail'],
      $item['date'],$item['time']
      );
    $result = mysqli_stmt_execute($stmt);
    // rest of your code
};    

Incidentally, you also had $con and $conn (2 'n') as your connect variable - hope you don't have this in your code.

I can't tell for certain but your code may be confusing the OO (object oriented) and procedural form of mysqli. Stick to one or the other (OO form ideally)

For example in your original code, say someone sent you a malicious JSON object similar to the following:

{
"id" : "hackerid",
"doctorName" : "I am a Hacker",
"doctorEmail": "hacker@hacker.com",
"date": "1999-12-31",
"time": ""); drop table doctor_visit_track; -- Muhahahaha "
}

...you would not be happy with the result.


I had a similar problem that turned out to be due to PHP magic quotes being enabled, and adding escape characters to the json string. Try disabling magic quotes in your php.ini:

magic_quotes_gpc = Off

链接地址: http://www.djcxy.com/p/53062.html

上一篇: 警告:为foreach()提供的参数无效

下一篇: 为foreach()警告提供的参数无效