2012-12-09 193 views
0

我有以下代碼:嵌套foreach循環不起作用

foreach($RSS_DOC->channel->item as $RSSitem) { 

    $item_id = md5(str_replace(array('\'', '"'), '', $RSSitem->title)); 
    $fetch_date = date("Y-m-j G:i:s"); //NOTE: we don't use a DB SQL function so its database independant 
    $item_title = str_replace(array('\'', '"', '(', ')', ' - ', '.'), '', $RSSitem->title); 
    $item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate)); 
    $item_url = $RSSitem->link; 

    $words = explode(' ', $item_title); 

    echo "Processing item '" , $item_id , "' on " , $fetch_date  , "<br/>"; 
    echo $item_title, " - "; 
    echo $item_date, "<br/>"; 
    echo $item_url, "<br/>"; 

    // Does record already exist? Only insert if new item... 

    $item_exists_sql = "SELECT item_id FROM rssingest where item_id = '" . $item_id . "'"; 
    $item_exists = mysql_query($item_exists_sql, $db); 
    if(mysql_num_rows($item_exists) < 1) { 

     echo "<font color=green>Inserting new item..</font><br/>"; 
     $item_insert_sql = "INSERT INTO rssingest(item_id, feed_url, item_title, item_date, item_url, fetch_date) VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')"; 
     $insert_item = mysql_query($item_insert_sql, $db); 

     foreach ($words as $value) { 

      $word_exists_sql = "SELECT id FROM words WHERE word = '" . $value . "'"; 
      $word_exists = mysql_query($word_exists_sql, $db); 

      if (mysql_num_rows($word_exists) < 1) { 
       $word_insert_sql = "INSERT INTO words(word, count) VALUES ('" . $value . "', '1')"; 
       $insert_word = mysql_query($word_insert_sql, $db); 
       echo "<font color=green>Inserting word ".$value."..</font><br/>"; 

      } else { 
       $word_update_sql = "UPDATE words SET count = count+1 WHERE word = '" . $value . "'"; 
       $update_word = mysql_query($word_update_sql, $db); 
       echo "<font color=green>Updating count for word ".$value."..</font><br/>"; 
      } 
     } 



    } else { 
     echo "<font color=blue>Not inserting existing item..</font><br/>"; 
    } 

    echo "<br/>"; 
} 

第一的foreach按預期工作,第二個只插入DB中的第一個RSS項目的第一個字,即使回聲的對於剩下的單詞顯示正確。

我錯過了什麼?

+2

[**請不要在新代碼中使用'mysql_ *'函數**](http://bit.ly/phpmsql)。他們不再被維護,[棄用過程](http://j.mp/Rj2iVR)已經開始。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 –

回答

1
$word_insert_sql = "INSERT INTO words(word, count) VALUES ('" . $value . "', count+1)"; 

究竟是count + 1應該來自哪裏。當然,這應該只是1

在任何情況下,如果您嘗試數據庫操作,在繼續之前檢查它們是否已經工作通常是個好主意。

+0

從測試代碼的更新部分剩餘的剩餘...將更新代碼 – andyderuyter

+0

事情是......將一個分解詞插入到數據庫中,但事實就是如此。 – andyderuyter

+0

@andy,請參閱我答案的第二部分。你應該檢查'mysql_query'是否返回true,並且調用'mysql_affected_rows'來查看有多少行被擊中。 – paxdiablo