2016-04-04 89 views
0

我一直在嘗試將RSS文章保存在我的數據庫中(來自RSS網址)並且正在工作。但現在我想防止插入重複的文章(行),我試過下面的代碼,但它不工作。每次運行時,它似乎都可以正常工作,除了它插入所有文章並且不會停止重複(文章存在新紀錄id 144)。這是爲什麼發生?如何避免在MySQL中插入重複行?

<?php 
$doc = new DOMDocument(); 
$doc->load('yoursite.com/rss.xml'); 
$arrFeeds = array(); 
foreach ($doc->getElementsByTagName('item') as $node) { 
    $itemRSS = array ( 
     'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 
     'description' => $node->getElementsByTagName('description')->item(0)->nodeValue, 
     'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 

    ); 
    array_push($arrFeeds, $itemRSS); 
} 

$mysqli = new mysqli('localhost', '', '', 'testdb'); 

if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

$check=mysqli_query($mysqli,"select * from `articles` where `title`=`title` and `description`=`description`"); 
$checkrows=mysqli_num_rows($check);if (!$check) { die('Invalid query: ' . mysql_error());} 

if($checkrows>0) { 
    echo "article exists"; 

    if ($stmt = $mysqli->prepare("INSERT INTO `articles` (`title`, `description`, `link`) VALUES (?, ?, ?)")) { 
     $stmt->bind_param('sss', $title, $description, $link);} 

    else {die("Errormessage: ". $mysqli->error);} 

    foreach($arrFeeds as $RssItem){ 
     $title = $RssItem["title"]; 
     $description = $RssItem["description"]; 
     $link = $RssItem["link"]; 

     $stmt->execute(); 
    } 

    printf ("New Record has id %d.\n", $mysqli->insert_id); 

    $stmt->close(); 
    $mysqli->close(); 
} 
?> 

回答

0

您的插入查詢是if($checkrows>0)條件的真正分支。把它移到假分支上,否則。

+0

感謝你的幫助,它現在可以正確排序。 – ika

0

您可以添加獨特的關鍵是你的articel id列,並使用INSERT IGNORE聲明