使用PHP ARRAY和for循环将Insert插入TABLE

时间:2016-11-12 23:27:58

标签: php sql oracle

我有一个来自数据库的php数组。我希望将此数组插入到不同的db / table中。两个字段(WEBINV_ID,HOSTNAME)是唯一的。我会每个脚本每天更新这些表。如果条目存在,则必须跳过插入并应使用更新。这工作得很好。但是如果我在php for循环中运行它,它只会将数组的第一个条目插入或更新到新表中 我用

// .h
struct S { void f() {} };

为此。 那是我的输入数组:

MERGE INTO TABLE ...

这是我的for循环,我试图插入或更新我的所有设备。

[0] => Array
    (
        [CI_ID] => 39778
        [NODEALIAS] => rt-2
        [NODE] => 10.1.2.3
        [SERIALNUMBER] => 8374378584
        [VENDORNAME] => Cisco
        [STATUS] => active
    )

[1] => Array
    (
        [CI_ID] => 72909
        [NODEALIAS] => rt-1
        [NODE] => 10.1.1.3
        [SERIALNUMBER] => 1276731237
        [VENDORNAME] => Cisco
        [STATUS] => active
    )...

我用“oci_bind_by_name”尝试了相同的代码,但结果是一样的,只有第一个条目用于数组。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

如果您使用的是oci_bind_by_name,我了解您使用的是Oracle数据库。

也许你应该这样做:

$insert_query = "insert all ";
foreach($router as $record) {
  $fields = "";
  $values = "";
  foreach($record as $field => $value) {
    $fields .= $field . ($field != 'STATUS' ? ',' : ""); // this is only if in the array the last field is STATUS - if it is not you might try to figure out last column diferently or remove last ',' differently
    $values .= "'" . $value . "'" . ($field != 'STATUS' ? ',' : ""); // this is only if in the array the last field is STATUS - if it is not you might try to figure out last column diferently or remove last ',' differently
  }
  $insert_query .= " into devices (" . $fields . ") values (" . $values . ") ";
}

上面将创建一个$ insert_query的查询,你只需要将它发送到数据库。 你需要弄清楚的唯一额外的事情是应引用哪些字段,哪些字段不引用。我引用了所有这些,因为Oracle应该能够正确地转换值 - 但是你需要仔细检查一下(我没有Oracle可用来检查它:))

我使用的SQL构造可以找到here

答案 1 :(得分:0)

我找到了一个解决方案,我将仅添加我的工作代码,这篇文章已经完成,我希望能帮助其他人。 这是代码:

for ($i = 0; $i < count($router); $i++) {
    $query = "MERGE INTO CORE_INTERFACES USING dual ON "
      // The next row is the match criteria, like If "HOSTNAME" AND "IFINDEX" exist, Then Update else INSERT NEW HOSTNAMES!   
      . "( HOSTNAME = '" . $hostname . "' AND IFINDEX = '" .    t trim($router_interface[0]) . "')" 
      . "WHEN MATCHED THEN UPDATE SET "
      . "IFNAME = '" . trim($router_interface[1]) . "',IFTYPE = '" . trim(clean_iftype($router_interface[2])) . "',IFADMINSTATUS = '" . trim(clean_output($router_interface[3])) . "',"
      . "LAST_UPDATE = CURRENT_TIMESTAMP "
. "WHEN NOT MATCHED THEN INSERT ("
      . "IF_ID,HOSTNAME,IFINDEX,IFNAME,IFTYPE,IFADMINSTATUS,"
      . "FIRST_SEEN "
      . ") VALUES ("
      . " core_interfaces_seq.nextval, "
      . "'" . $hostname . "',"        //$HOSTNAME
      . "'" . trim($router_interface[0]) . "',"       //ifIndex
      . "'" . trim($router_interface[1]) . "',"       //ifName
      . "'" . trim(clean_iftype($router_interface[2])) . "',"         //ifType
      . "'" . trim(clean_output($router_interface[3])) . "',"         //ifAdminState
      . " CURRENT_TIMESTAMP )";
   $stid = oci_parse($gnedb, $sql);
}