简体   繁体   English

检查MYSQL以查看是否已存在条目,否则

[英]Check MYSQL to see if a entry already exists without if else

Hi I have a long page of code with multiple if else statemets, what i would like to do is check a database to see if that Ip address is already in the table 嗨,我有一长串代码,其中包含多个ifmeta statemets,我想做的是检查数据库以查看该IP地址是否已在表中

currently i am doing it like this 目前我正在这样做

     $result = mysql_query("SELECT * FROM masterip_details WHERE    ip_address='$ip_address' AND client_id='$client_id'") or die(mysql_error());
     $num_rows = mysql_num_rows($result);
    //IF THE RESULT IS MORE THAN 0, THIS MEANS THAT THEY ARE A RETURNING VISITOR
    if( $num_rows > 0 ) {
         /// Add returning Script here  

    }  else {
        //Add code

         }

Is there a way i could do this with out the if else statement?, so for example if the record was in the database just return a value of 1. 有没有办法使用if else语句执行此操作?例如,如果记录在数据库中,则仅返回值1。

Thanks, any suggestions would be appreciated. 谢谢,任何建议将不胜感激。

You can use count to get the number of rows with that value. 您可以使用count获得具有该值的行数。

$result = mysql_query("SELECT count(*) FROM masterip_details WHERE    ip_address='$ip_address' AND client_id='$client_id'") or die(mysql_error());

return $result > 0;  //returns a boolean

This way you will get a 0 if the value doesn't exist on the database and a number higher than 0 if it does. 这样,如果数据库中不存在该值,您将获得0如果存在,则该数字将高于0。

Make use of SELECT IF EXISTS on MySQL. 在MySQL上使用SELECT IF EXISTS

SELECT IF( EXISTS(
             SELECT *
             FROM  masterip_details
             WHERE `ip_address`=? AND `client_id`=?), 1, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM