简体   繁体   中英

Inserting data two times in foreach loop with multiple arrays

I have a working code

<?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();

?>

But data is inserting twice with every run of this script. I am using delete statement to delete the data first before inserting new one.Can anyone please help me solve this twice problem. Here is teh screenshot of twice Data filled . http://i.imgur.com/7IM1mOE.png?1

NEW EDIT

Here is the INSERT QUERY echo http://pastebin.com/btZ7f85a The data is not duplicate.

Thanks in advance

This is untested, but try something like this. I changed the delete to TRUNCATE which will drop all data in the table. I also changed the way the INSERTs work rather than 1 long ass insert I changed it to multiple inserts. There shouldn't be a huge performance hit. Give it a try, let me know.

<?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());
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM