How can I keep from inserting duplicate rows in MySQL?

时间:2016-04-04 17:00:35

标签: php mysql rss

I have been trying to save RSS articles in my database (from RSS URL) and it is working. But now I want to prevent inserting duplicate articles (rows) and I have tried the coding below but it doesn't work. Every time it runs, it all seems to work fine except it inserts all the articles and doesn't stop the duplication (article exists New Record has id 144). Why is this happening?

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

2 个答案:

答案 0 :(得分:0)

Your insert query is in if($checkrows>0) condition's true branch. Move it to the false branch, under else.

答案 1 :(得分:0)

您可以在关键字ID列中添加唯一键,并使用INSERT IGNORE语句