MYSQL PHP Foreach语句只提交第一个insert into语句

时间:2017-03-10 00:31:34

标签: php mysql xml

我正在尝试使用foreach语句将xml文件加载到我的MYSQL数据库中。由于某种原因,它成功地循环遍历XML文件,但似乎只有第一次通过循环实际发送到数据库。

<?xml version="1.0" encoding="utf-8" ?>

<chatcoderadmin>
  <!-- Table Alarcos -->
    <Alarcos>
        <Alarcos_ID>12</Alarcos_ID>
        <Device_ID>16cf10d0-5154-444e-96ad-46e913ac9761</Device_ID>
        <Sender>4849941474</Sender>
        <Receiver>2157389113</Receiver>
        <Message>Hi Connor</Message>
        <Service_Center></Service_Center>
        <SMSStatus>0</SMSStatus>
        <Timestamp>2015-09-10 14:09:45</Timestamp>
        <Replace_Bit_Set>0</Replace_Bit_Set>
        <Reply_Path_Exists>0</Reply_Path_Exists>
        <Is_Status_Report>0</Is_Status_Report>
    </Alarcos>
    <Alarcos>
        <Alarcos_ID>13</Alarcos_ID>
        <Device_ID>f0bd524e-2289-47b3-b9c6-65c6af2dce64</Device_ID>
        <Sender>4849941470</Sender>
        <Receiver>266781</Receiver>
        <Message>BstFreeMsg: Select privacy choices for new account or line(s). More info on how to opt in/out of Mobile Ads &amp; Reporting programs at boostmobile.com/privacy. </Message>
        <Service_Center></Service_Center>
        <SMSStatus>0</SMSStatus>
        <Timestamp>2015-09-10 11:30:01</Timestamp>
        <Replace_Bit_Set>0</Replace_Bit_Set>
        <Reply_Path_Exists>0</Reply_Path_Exists>
        <Is_Status_Report>0</Is_Status_Report>
    </Alarcos>
</chatcoderadmin>

这是我用来处理XML的PHP​​代码

<?php
    $xml = simplexml_load_file("test.xml") or die("Error: Cannot create object");

    $createAlarcos = $conn->prepare("INSERT INTO Alarcos_Data (alarcos_id, device_id, sender, receiver, message, alarcos_timestamp) VALUES (?,?,?,?,?,?)");

    $createAlarcos->bind_param("isssss",$alarcos_id, $device_id, $sender, $receiver, $message, $alarcos_timestamp);

    foreach($xml->children() as $Alarcos) { 

        $alarcos_id = $Alarcos->Alarcos_ID;
        $device_id = $Alarcos->Device_ID;
        $sender = $Alarcos->Sender;
        $receiver = $Alarcos->Receiver;
        $message = $Alarcos->Message;
        $alarcos_timestamp = $Alarcos->Timestamp;

        $createAlarcos->execute();

    } 

    $createAlarcos->close();
    ?>

1 个答案:

答案 0 :(得分:0)

您在两个XML元素中都拥有相同的ID。可能alarcos_id是数据库表中的主键,因此不会覆盖。这是检查错误结果的一个很好的理由; execute()可能会返回false。

...
if (!$createAlarcos->execute()) {
    foreach ($createAlarcos->error_list as $err) {
        echo "Error $err[errno]: $err[error]<br/>\n";
    }
}