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条)

报告相同问题?

悬赏问题

  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection