将成功插入的记录捕获到阵列中

时间:2019-03-22 18:03:32

标签: php mysql arrays pdo

我正在使用PDO将记录从一个表插入到另一个表中。

我正在尝试捕获已成功插入到另一个表中的记录,同时还捕获了可能无法插入的记录。

<?php
  $checkcontainer = $_POST['checkcontainer'];
  $checkscac = $_POST['checkscac'];
  $comment = $_POST['comment'];
  $time = date('Y-m-d H:i:s');

  $containerSuccess = array();
  $containerFail = array();

  $count = count($checkcontainer);

  for($i = 0; $i < $count; $i++)
  {
    $container = $checkcontainer[$i];
    $scac = $checkscac[$i];

    $insert = $dbc->prepare("INSERT IGNORE INTO trucker_edi_comms (container, scac, fac_comments, fac_datestamp) VALUES (:ucont,:uscac,:ucomm,:utime);");

    $insert->execute([
        'ucont' => $container,
        'uscac' => $scac, 
        'ucomm' => $comment,
        'utime' => $time
    ]);

    if($insert)
    {
        $containerSuccess = $container;
        //echo "containers saved: " . $containerSuccess;
    }
    else
    {
        $containerFail = $container;
        //echo "containers failed: " . $containerFail;
    }
  }

  echo "containers saved: " . $containerSuccess;
?>

INSERT语句起作用。我还可以将$ containerSuccess数组设置为$ container。如果成功插入3个容器,则FOR循环内部的输出如下所示:

containers saved: TEST123456789containers saved: TEST98642357containers saved: TEST65897531

但是我需要能够在FOR循环之外回显$ containerSuccess。当前,输出如下所示:

containers saved: TEST65897531

我只能抓取最后保存的容器。

我需要在FOR循环之外回显所有容器以显示给用户。

我如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您的示例尝试使用字符串填充声明的数组,因此您在有关变量类型的正确位置上。循环完成后,您可以填充一个数组以输出保存/失败的容器,如果希望它在一行上输出,请使用implode()作为输出:

<?php
  $checkcontainer = $_POST['checkcontainer'];
  $checkscac = $_POST['checkscac'];
  $comment = $_POST['comment'];
  $time = date('Y-m-d H:i:s');

  $containerSuccess = array();
  $containerFail = array();

  $count = count($checkcontainer);

  for($i = 0; $i < $count; $i++)
  {
    $container = $checkcontainer[$i];
    $scac = $checkscac[$i];

    $insert = $dbc->prepare("INSERT IGNORE INTO trucker_edi_comms (container, scac, fac_comments, fac_datestamp) VALUES (:ucont,:uscac,:ucomm,:utime);");

    $insert->execute([
        'ucont' => $container,
        'uscac' => $scac, 
        'ucomm' => $comment,
        'utime' => $time
    ]);

    if($insert)
        $containerSuccess[] = $container;
    else
        $containerFail[] = $container;

  }

  echo "containers saved: " . implode(', ', $containerSuccess);
  echo "containers failed: " . implode(', ', $containerFail);

?>