【问题标题】:Invalid argument supplied for foreach() warning为 foreach() 警告提供的参数无效
【发布时间】:2015-07-24 08:43:27
【问题描述】:

我想在 mysql 表中插入 json 数组数据。我已经写了这段代码。

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

当我使用 xampp 时,上面的代码运行良好。但是,当我将此代码上传到服务器时,相同的代码会发出警告“foreach() 提供的参数无效”并且未插入表中。但是在 xampp 中使用,代码工作正常并成功插入数据。有人帮帮我..

【问题讨论】:

  • var_dump($array) 看看你得到了什么。
  • @b0s3 我得到 NULL..
  • 这意味着$json 无效JSON。检查一下。
  • 如果有帮助,您可以通过json_last_error_msg() 获取有关json_decode() 遇到的错误的更多信息
  • @b0s3 但是为什么使用 xampp 时相同的代码可以成功运行..

标签: php mysql


【解决方案1】:

不是一个完整的答案,而是观察到您的代码容易受到 SQL 注入的影响。试试:

$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
};    

顺便说一句,您还使用 $con 和 $conn (2 'n') 作为连接变量 - 希望您的代码中没有这个。

我无法确定,但您的代码可能会混淆 OO(面向对象)和 mysqli 的过程形式。坚持一个或另一个(理想的 OO 形式)

例如,在您的原始代码中,假设有人向您发送了一个类似于以下内容的恶意 JSON 对象:

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

...你不会对结果感到满意。

【讨论】:

  • 感谢您告诉我这个错误。我已经修复了这个错误,并使单个连接 $con 变量。其实我不是php人..
  • 作为您原始代码中的示例,如果有人以 JSON 格式向您发送一个 'time' 为 "); delete * from doctor_visit_track;" 他们可以擦除您的 doctor_visit_track桌子。把其他东西放在这里可能会擦除你的整个数据库
  • 是的,但你得调试一下,我在上班,明显没测试过
  • 谢谢我使用了你的代码,也使用了php官方文档,并且能够成功地完成我的工作..
【解决方案2】:

我有一个类似的问题,原来是由于启用了 PHP 魔术引号,并将转义字符添加到 json 字符串。尝试在 php.ini 中禁用魔术引号:

magic_quotes_gpc = 关闭

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多