首页 > 文章列表 > 如何用PHP循环插入JSON数组到数据库?

如何用PHP循环插入JSON数组到数据库?

417 2024-12-21

如何用PHP循环插入JSON数组到数据库?

利用循环插入 json 数组到 php 数据库中

想要将从前端传入的 json 数组逐条插入数据库,可以采用循环处理的方式,具体步骤如下:

  1. 解码 json 数组
$data = json_decode($datas);
  1. 循环遍历数组
foreach ($data as $row) {
    // 构建插入 SQL 语句
    $sql = "INSERT INTO `tablename` (";
    $sql .= "`id`, `name`, ..., "; // 替换为表中的字段名称
    $sql .= "`field_name`) ";
    $sql .= "VALUES ";
    $sql .= "($row->id, '$row->name', ..., '$row->field_name');";

    // 执行 SQL 语句
    $result = mysqli_query($conn, $sql);

    // 检查执行结果
    if (!$result) {
        echo "插入数据失败: " . mysqli_error($conn);
        exit;
    }
}

注意事项:

  • 务必替换 tablename、id、name 等字段名称为表中的实际值。
  • 实际批量插入数据建议分批处理,一次插入数百或数千条数据,避免单次 sql 语句过大导致执行失败。
来源:1733004373