php - 如何使用 PHP 在 MySQL 中插入值数组

标签 php mysql

如何将数组内的值插入到数据库中各自的行中?

这是数组:

  $nombre_bene = $_POST['nombre-bene'];
  $cedula_bene = $_POST['ci-bene'];
  $nacimiento_bene = $_POST['nacimiento-bene'];
  $parentezco_bene = $_POST['parentezco-bene'];
  $servicios_bene = $_POST['servicios-bene0'];
  $id_titular =  $_POST['plan-tipo'];

  $data_beneficiario = array(
    'nombre' => $nombre_bene,
    'cedula' => $cedula_bene,
    'nacimiento' => $nacimiento_bene,
    'parentezco' => $parentezco_bene,
    'id' => $id_titular,
    'servicios' => $servicios_bene
  );

问题是每个 $_POST 都是一个数组(因为我需要这样)

我尝试在 $data_beneficiario 数组中使用 foreach ..但问题是每个变量都是一个索引数组..我正在用准备好的 PHP 函数注入(inject)这些值

  $statement2 = $connection->prepare(" INSERT INTO beneficiarios (nombre_bene, cedula_bene, fechan_bene, parentezco, id_titular_bene, servicios_adicionales) VALUES(?,?,?,?,?,?) ");
      $statement2->bind_param("ssssis", $nombre_bene, $cedula_bene, $nacimiento_bene, $parentezco_bene, $id_titular, $servicios_bene);

但我不知道如何以每个值进入其自己的列的方式插入值。我将不胜感激的帮助!

最佳答案

首先将各个字段数组组合成行。

$rows = array_map(
    null,
    $_POST['nombre-bene'],
    $_POST['ci-bene'],
    $_POST['nacimiento-bene'],
    $_POST['parentezco-bene'],
    $_POST['servicios-bene0'],
    $_POST['plan-tipo']
);

接下来,插入每一行:

for ($rows as $row) {
    $statement = $connection->prepare('insert into beneficiarios (nombre_bene, cedula_bene, fechan_bene, parentezco, id_titular_bene, servicios_adicionales) values (?,?,?,?,?,?)');
    $statement->bind_param("ssssis", $row[0], $row[1], $row[2], $row[3], $row[4], $row[5]);
    $statement->execute() or die $connection->error;
}

关于php - 如何使用 PHP 在 MySQL 中插入值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574994/

相关文章:

php - 休息;与继续;与返回;

php - 使用 PHP/Python 下载 url 中的特定文件

php - 如何使用 PHP 和 MySQL 从数据库中过滤日期和日期

php - 我如何找出哪个页面安装了我的 Facebook 应用程序/哪个页面正在加载我的应用程序

php - 在 PHP 中将 ASCII 转换为纯文本

mysql - webSQL 中的复合主键

mysql - 在 DATETIME 字段上按月分组

MySQL 建立索引时超时

php - Twitter 应用程序开发 : PHP or javascript. ..请帮助

php - 以 PDO 格式重写循环内的查询