2013-04-26 117 views
0

我有一個工作代碼插入數據foreach循環兩次與多個陣列

<?php 

$con = mysql_connect('localhost','test','test'); 
mysql_select_db('test',$con); 


require_once("xml2json.php"); 

$testXmlFile = 'myxml.xml'; 

$xmlStringContents = file_get_contents($testXmlFile); 
$jsonContents = ""; 
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents); 
$obj =json_decode($jsonContents); 
$rows = array(); 
foreach($obj->rss->channel->item as $item) { 

$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')"; 

} 
     $del_horoscope = "delete from jos_horoscope"; 
     mysql_query($del_horoscope); 

     $query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows); 
     print_r ($query); 
     mysql_query($query); 
    // Do the query - do NOT show the output of mysql_error() in a production environment! 
    if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error(); 

?> 

但數據與該腳本的每次運行插入兩次。我在使用刪除語句刪除數據之前插入新的one.Can任何人請幫助我解決這個問題。這裏是兩次數據填充的屏幕截圖。 http://i.imgur.com/7IM1mOE.png?1

新的編輯

這裏是INSERT QUERY回聲http://pastebin.com/btZ7f85a 的數據不重複。

在此先感謝

+0

你不必通過這個例子的外觀工作代碼,你忘了關關密碼字符串在'的mysql_connect()';) – 2013-04-26 02:32:19

+0

是數據的XML複製1)? 2)在json? 3)在foreach循環? – Patashu 2013-04-26 02:32:44

+0

@DarylGill其實在發佈這裏之前有一個錯字錯誤。謝謝我現在編輯它。 :) – Yogus 2013-04-26 02:35:28

回答

0

這是未經測試,但嘗試這樣的事情。我將刪除更改爲TRUNCATE,這將刪除表中的所有數據。我也改變了INSERTs的工作方式,而不是1個長屁股插入,我將它改爲多個插入。不應該有巨大的表現。試試看,讓我知道。

<?php 

$con = mysql_connect('localhost','test','test'); 
mysql_select_db('test',$con); 

require_once("xml2json.php"); 

$testXmlFile = 'myxml.xml'; 

$xmlStringContents = file_get_contents($testXmlFile); 
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents); 
$obj =json_decode($jsonContents); 
$rows = array(); 

foreach($obj->rss->channel->item as $item) 
{ 
    $rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')"; 
} 

// Remove Data in Table. 
$truncate = mysql_query("TRUNCATE TABLE jos_horoscope"); 

foreach($rows as $row) 
{ 
    $query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES $row"; 
    $result = mysql_query($query) or die(mysql_error()); 
} 
?> 
+0

謝謝@ChrisG但現在錯誤是 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'今天有什麼特別的'附近使用正確的語法','您在本月的第25天出生(7 ener'在第1行) :( – Yogus 2013-04-26 02:40:53

+0

更新,對不起,忘了在$ row前加VALUES。再試一次! – ChrisG 2013-04-26 02:43:41

+0

謝謝@ChrisG工作過的:D:D:D非常感謝..我從你那裏學到了新東西..謝謝 – Yogus 2013-04-26 02:48:45