簡體   English   中英

php Foreach循環僅提取最后一條記錄

[英]php Foreach Loop only extracting last record

這是我的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> 

嘗試在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());
  }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM