插入数据foreach循环两次与多个阵列
问题描述:
我有一个工作代码插入数据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 的数据不重复。
在此先感谢
答
这是未经测试,但尝试这样的事情。我将删除更改为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());
}
?>
你不必通过这个例子的外观工作代码,你忘了关关密码字符串在'的mysql_connect()';) – 2013-04-26 02:32:19
是数据的XML复制1)? 2)在json? 3)在foreach循环? – Patashu 2013-04-26 02:32:44
@DarylGill其实在发布这里之前有一个错字错误。谢谢我现在编辑它。 :) – Yogus 2013-04-26 02:35:28