2
我想用foreach語句將xml文件加載到我的MYSQL數據庫中。它由於某種原因成功地在XML文件中循環,但似乎只有通過循環的第一次實際發送到數據庫。MYSQL PHP Foreach語句只提交第一個插入語句
<?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 & 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
$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();
?>
這看起來不錯;我假設'$ conn'是mysqli而不是PDO?任何錯誤?你有沒有添加調試,以確保你實際上處理XML中的多個孩子? – miken32
$ conn是mysqli。我相信它正在處理不止一個孩子。當我在foreach中回顯出alarcos_id時,它給出了它的兩個實例。 – kirie
我發現在某些情況下綁定到不存在的變量可能會造成麻煩。我通常在綁定它們之前將變量聲明爲空。 – miken32