PHP MySQL 插入数组

PHP MySQL Insert array

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

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

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

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

将每个 ? 替换为 {$arr['xxxxx']} 其中 xxxxx 是您的数组键

确保对变量进行良好的转义以防止SQL注入

提示:您可以使用 PDO 或准备好的语句

我不是很了解你的代码,但起初你的json不好,在post上,这是一个正确的例子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)