Mysql如果数据存在,则不要再次插入 [英] Mysql if data exists then do not insert it again

查看:360
本文介绍了Mysql如果数据存在,则不要再次插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的这段代码通过使用PHP curl函数从另一个网站获取数据.一切正常,但是当网站将重新加载或刷新时,我正在数据库中获取重复的数据.
重复的数据截图

I use this code below for getting data from a different website by using PHP curl function.everything is working fine but I am getting duplicate data into my database when the website will reload or refresh.
duplicate data screenshot

基于以下代码,如果在Mysql数据库中已经存在数据,是否有任何理由在重新加载时停止插入重复数据?我在Google上搜索了有关此问题的信息,但未获得任何有用的信息.

does there have any why based on this code below to stop inserting duplicate data on reload if the data already exist in the Mysql database? I search on google about this issue but don't get any useful information.

if(isset($_POST['url'],$_POST['theme'])){

    $db = new Mysqli("localhost" , "iamniloy_wp###" , "(5uSE6[3OP" , "iamniloy_#@");

    $url = $db->real_escape_string($_POST['url']);
    $theme = $db->real_escape_string($_POST['theme']);


    $query = "INSERT INTO twist_data ( url,theme ) VALUES ('$url','$theme')";
    $db->query($query);

    }

推荐答案

如果由于某种原因无法添加唯一索引,则可以使用EXISTS检查已存在的记录:

If you can't add a unique index for whatever reason, you can use EXISTS to check for an already existing record:

INSERT INTO twist_data (url, theme)
SELECT * FROM (SELECT '$url','$theme') AS tmp
WHERE NOT EXISTS (
    SELECT * FROM twist_data WHERE url = '$url' AND theme = '$theme'
)

这篇关于Mysql如果数据存在,则不要再次插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆