doukongyong44772 2016-04-04 17:00
浏览 21
已采纳

如何防止在MySQL中插入重复的行?

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
", 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.
", $mysqli->insert_id);

    $stmt->close();
    $mysqli->close();
}
?>
  • 写回答

2条回答 默认 最新

  • duanchen6423 2016-04-04 17:05
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 等差数列中的素数个数
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证