php Foreach循环只提取最后一条记录

时间:2017-01-19 06:46:10

标签: php mysql sql-server xml

这是我的php代码,用于从xml中提取数据并插入到我的mysql表中。 为什么这段代码只提取最后的xml记录?此代码提取并插入
100 CAPITAL TOWERS,MS ,Harare,JACKSON,MS,39201,100 CAPITAL TOWERs,100 CAPITAL TOWERS进入表格,这是xml的最后一条记录 我们需要帮助来插入xml从上到下的所有记录。

<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
if(!$vals=simplexml_load_file('local1.xml'))
{
    trigger_error('Error reading XML file',E_USER_ERROR);
}
foreach ($vals as $record) {    
    $country = $record->country;
    $state = $record -> state ;
    $district = $record->district;
    $city = $record->city;   
    $post_office = $record->post_office;
    $postal_code = $record->postal_code;
    $wings = $record->wings;
    $house_no = $record->house_no;
}
$sql="INSERT INTO address(country, state,district,city,post_office,postal_code,wings,house_no)
VALUES
('$country','$state','$district','$city','$post_office','$postal_code','$wings','$house_no')";
if (!mysql_query($sql,$con))
{
    die('Error: ' . mysql_error());
}
echo "Records added";
mysql_close($con)
?>

local1.XML:

<?xml version="1.0" encoding="UTF-8" ?>
<records>
    <record>
        <country>100 OLD MILL CREEK RD</country>
        <state>NC  </state>
        <district>Harare</district>
        <city>FRANKLIN</city>
        <post_office>NC  </post_office>
        <postal_code>28734</postal_code>
        <wings>100 OLD MILL CREEK RD</wings>
        <house_no>100 OLD MILL CREEK RD</house_no>
    </record>
    <record>
        <country>100 CAPITAL TOWERS</country>
        <state>MS  </state>
        <district>Harare</district>
        <city>JACKSON</city>
        <post_office>MS  </post_office>
        <postal_code>39201</postal_code>
        <wings>100 CAPITAL TOWERS</wings>
        <house_no>100 CAPITAL TOWERS</house_no>
    </record>
</records> 

1 个答案:

答案 0 :(得分:0)

尝试在foreach循环中添加sql查询,如下所示:

foreach ($vals as $record) {    
 $country = $record->country;
 $state = $record -> state ;
 $district = $record->district;
 $city = $record->city;   
 $post_office = $record->post_office;
 $postal_code = $record->postal_code;
 $wings = $record->wings;
 $house_no = $record->house_no;

$sql="INSERT INTO address(country, state,district,city,post_office,postal_code,wings,house_no)
   VALUES
    ('$country','$state','$district','$city','$post_office','$postal_code','$wings','$house_no')";

  if (!mysql_query($sql,$con))
 {
  die('Error: ' . mysql_error());
  }
 }