How to check if a value already exists to avoid duplicates?

前端 未结 17 1068
小鲜肉
小鲜肉 2020-12-02 23:13

I\'ve got a table of URLs and I don\'t want any duplicate URLs. How do I check to see if a given URL is already in the table using PHP/MySQL?

17条回答
  •  长情又很酷
    2020-12-02 23:30

    $url = "http://www.scroogle.com";
    
    $query  = "SELECT `id` FROM `urls` WHERE  `url` = '$url' ";
    $resultdb = mysql_query($query) or die(mysql_error());   
    list($idtemp) = mysql_fetch_array($resultdb) ;
    
    if(empty($idtemp)) // if $idtemp is empty the url doesn't exist and we go ahead and insert it into the db.
    { 
       mysql_query("INSERT INTO urls (`url` ) VALUES('$url') ") or die (mysql_error());
    }else{
       //do something else if the url already exists in the DB
    }
    

提交回复
热议问题