【问题标题】:Insert JSON into Mysql problem (ajax/php)将JSON插入Mysql问题(ajax/php)
【发布时间】:2020-01-16 09:40:44
【问题描述】:

我在将制表符分隔的文本放入文本区域后构建了一个 Json(来自此 codepen 示例):

[
  {
    "0": "2019-08-31",
    "1": "Bank Exp.",
    "2": "EUR"
  },
  {
    "0": "2019-08-31",
    "1": "Legal",
    "2": "EUR"
  },
  {
    "0": "2019-08-31",
    "1": "Legal",
    "2": "EUR"
  }
]

并存储在变量中:

jsonString = JSON.stringify(data, null, 2);

然后我通过 ajax 将这个 json 传递给一个 php 文件

var options = {
                  type: "POST",
                  url: "test.php",
                  data: { test: jsonString },
                  dataType: 'json',
                  success: function( data, status, xhr ) {
                    alert ("php:"+data);

                  },
                  error: function( xhr, status, error ) {
                   alert (data);
                  }
                };
                $.ajax( options );

在我的“test.php”文件中处理 0、1、2 列中不同行的简单 MYSQL 插入:

<?php
$host="localhost";
$user="renaud";
$pass="Mod100572$";
$db="accounting";
$con= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!!!");
$test = utf8_encode($_POST['test']);
$data_array = json_decode($test);
foreach($data_array as $row) {

    $query .= "INSERT INTO `test` set
          `field1`  = '".$row['0']."',
          `field2`  = '".$row['1']."',
          `field3`  = '".$row["2"]."';";
}
if(mysqli_multi_query($con, $query)) {
    $msg = "success";
} else {
    $msg = "Something wrong! Please try again.";
}
mysqli_close($con);
?>

我显然没有实现将我的 '$_POST['test']' 转换为正确的数组,并且循环仅获取 '[' 值。它被认为是一个字符串,而不是一个数组。

我尝试了其他参数,例如 $data_array = json_decode($test,true);没有运气。

非常感谢任何有助于理解我的错误的帮助...

【问题讨论】:

  • 当您使用$row['0'] - 您应该使用$data_array = json_decode($test,true); 解码数据。你试过用var_dump($data_array);之类的东西来调试它吗?
  • 还注意到 - 你没有在循环之前设置 $query,我总是会使用类似 $query = ""; 的东西来确保。
  • 尽量避免mysqli_multi_query。你不需要使用它,如果滥用它可能会非常危险。

标签: php mysql json ajax


【解决方案1】:

插入语法错误

$query .= "INSERT INTOtestVALUES ( field1= '".$row['0']."', field2= '".$row['1']."', field3= '".$row["2"]."');";

【讨论】:

    猜你喜欢
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2013-02-22
    • 1970-01-01
    相关资源
    最近更新 更多