尝试将列数据从json数组插入mysql

帕特里克·NY:

我试图用php将JSON数组(对象?!)插入mysql。当数据作为行通过时,我可以处理!但是,我不得不以其他方式导出数组,现在我无法弄清楚了。之后$array=json_decode($posted,true);,我的数组如下所示:

(
    [0] => Array
        (
            [0] => Allen, test
            [1] => Anderson, Jayson
            [2] => Barrett, Kayla
            [3] => Bennett, Amira
        )

    [1] => Array
        (
            [0] => [email protected]
            [1] => [email protected]
            [2] => [email protected]
            [3] => [email protected]
        )
)

如何将其放入输出的foreach循环中:

insert into table (name, email) values("Allen, test","[email protected]")
insert into table (name, email) values("Anderson, Jayson","[email protected]")
... etc?

当数据为“行”格式时,对我来说很容易..

          foreach($array as $row)
          {   
$query="insert into table (name, email) values(\"$row[0]\",\"$row[1]\")";
$doit = mysqli_query($con,$query);
          }

但是,既然数组不是逐行通过的,我就无法弄清楚。

耶普鲁比奥:

一种方法是循环$ row [0]并使用键获取两个值:

foreach($row[0] as $key => $value) {
    $name = $row[0][$key];
    $email = $row[1][$key];
    $query = "insert into table (name, email) values('$name', '$email')";
    $doit = mysqli_query($con,$query);
}

工作样本

但是,我强烈建议您在查询中使用准备好的语句而不是字符串变量,以防止受到SQL注入攻击。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章