PHP MySQL 插入数组

标签 php mysql arrays json insert

我无法从这个数组中插入值。这里的例子:

$arr = json_decode($_POST['dynfields'], true);
    //{"dynfields":{"dynfields[0][DescRepair]":"Desc repair","dynfields[0][NestParts]":"Parts","dynfields[0][EdPrice]":"10","dynfields[0][DateRepair]":"2015-07-20","dynfields[1][DescRepair]":"Desc repair","dynfields[1][NestParts]":"Parts","dynfields[1][EdPrice]":"5","dynfields[1][DateRepair]":"2015-07-20"}}

    foreach ($arr as $key => $fieldArray ) {
        foreach($fieldArray as $k => $v) {
            echo $k . " - " . $v . "<br>"; // result: dynfields[0][DescRepair] - Desc repair
                                            dynfields[0] [NestParts] - Parts
                                            dynfields[0][EdPrice] - 10
                                            dynfields[0][DateRepair] - 2015-07-20
                                            dynfields[1][DescRepair] - Desc repair
                                            dynfields[1][NestParts] - Parts
                                            dynfields[1][EdPrice] - 5
                                            dynfields[1][DateRepair] - 2015-07-20

        }
        //$query = mysqli_query($mysqli, "INSERT INTO repair (DescRepair, NestParts, EdPrice, DateRepair) VALUES ('?', '?', '?', '?')") or die(mysqli_error($mysqli));  
    }

这是我的代码,但我不知道如何将值插入数据库。你能给我任何建议吗?谢谢。

最佳答案

我不太理解你的代码,但起初你的 json 不好,在帖子中,这是一个正确的 json 的例子:

{
"dynfields": [
    {
        "DescRepair": "Desc repair",
        "NestParts": "Parts",
        "EdPrice": "10",
        "DateRepair": "2015-07-20"
    },
    {
        "DescRepair": "Desc repair",
        "NestParts": "Parts",
        "EdPrice": "5",
        "DateRepair": "2015-07-20"
    }
  ]
}

然后您可以使用 dynfields 数据创建一个 foreach:

$myvar = json_decode($json,true);
$data = $myvar['dynfields'];


    foreach(array_keys($data) as $index){
        var_dump($data[$index]);
    }

然后你会得到这样的东西(var_dump):

 array (size=4)
      'DescRepair' => string 'Desc repair' (length=11)
      'NestParts' => string 'Parts' (length=5)
      'EdPrice' => string '10' (length=2)
      'DateRepair' => string '2015-07-20' (length=10)
 array (size=4)
      'DescRepair' => string 'Desc repair' (length=11)
      'NestParts' => string 'Parts' (length=5)
      'EdPrice' => string '5' (length=1)
      'DateRepair' => string '2015-07-20' (length=10)

关于PHP MySQL 插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31544113/

相关文章:

php - mySQL 查询不存在

MySQL语法错误

c++指针/数组区别

javascript - 交换数组中的两个值

python - 物理尺寸和阵列尺寸

php - 更改了 MySql 中的表名 => symfony 代码中的错误

javascript - Highcharts 仪表在 IE8 中不起作用

mysql - 创建触发器以对同一个表进行条件更新

php - Laravel 5.5 在点击时使用 ajax 调用删除项目

php - 来自 Twitter API 的 JSON 包含\u2019