PHP MySQL foreach只插入第一个数组而没有循环

时间:2017-12-02 10:44:14

标签: php mysql

<?php
   require 'db-config.php';

   $results = simplexml_load_file('data.xml'); 

   foreach ($results->ROW as $resultinfo) {

    $id=$resultinfo->DATE;
    $name=$resultinfo->NAME;
    $address=$resultinfo->ADDRESS; 

    // insert not works in loop, only first row inserted    
    $sql = "INSERT INTO MyDB
    (id, name, address) 
    VALUES 
    ('$id', '$name', '$address')
    ON DUPLICATE KEY UPDATE 
    id = '$id'";    

    // echo works in loop
    echo ‘<div>’.$name.’</div>’;    
    echo ‘<div>’.$address.’</div>’; 

   }

    // Close Connection
   $conn->close();
   ?> 

在foreach内部,echo正在工作并按预期列出所有数据,sql insert无法正常工作,因为它只插入第一行,thx再次帮助!

1 个答案:

答案 0 :(得分:0)

小心你的单引号:

 $sql = "INSERT INTO MyDB
    (id, name, address) 
 VALUES 
    ('$id->ID', '$name', '$address')
 ON DUPLICATE KEY UPDATE 
    id = '$id'"; 

 mysql_query("INSERT INTO MyDB
    (id, home_score, away_score) 
 VALUES 
    ('$id->FIXTURE_ID', '$name', '$address')
 ON DUPLICATE KEY UPDATE 
    id = '$id'");