简体   繁体   中英

How to get which condition has failed if any in a single sql query

This might be odd or not... but I need to find out which condition out of 3 has failed if any...
I explain...
In my query I have 3 condition if all goes fine then no problem, but if one of those conditions fail I need to know which condition or conditions have fail so that I can build a proper response...
Example:

if(strlen($k) == 16 && filter_var($em, FILTER_VALIDATE_EMAIL)) {
        $con = $c->Con();
        $q = $con->query("SELECT COUNT(*) FROM table WHERE v = '$k' AND ema = '$em' AND ve = '0'");
        $r = $q->fetch_row();
        if($r > 0) { $q = $con->query("UPDATE table SET ve = '1' WHERE v = '$key' AND emails = '$em'");
            if($q){
                $mss = 'Ready'; // MS 1
            }
        } else {
            $mss = 'It was ready'; // MS 2
        }
    } else {
        $mss = 'Something is wrong!'; // MS 3
    }

So the first query has 3 conditions if all are ok then go to the next "query", BUT, how do I know is one of the conditions fail?... what if [v] is not a match, or if the email is not a match or if ve is not a match... that way I can show a proper message on the MS 2.... instead of a general message...
if v is not equal to $k then $mss = 'Your key is not a match';
if emails is not equal to $ema then $mss = 'Your email was not fund';
if ve is not equal to 0 then $mss = 'Your key has no value';

the thing is that I would like to keep it as short and clean as possible, I can do a separate query for each one of the conditions which is a lazy way to do it but effective...

I can come up with a clunky solution that mostly shifts the work to PHP.

  1. Change you query to SELECT the rows using ORs. To return the set of possible rows.

SELECT v, ema, ve FROM table WHERE v = '$k' OR ema = '$em' OR ve = '0';

  1. Now go through this result set to check the conditions.

Pseduocode

while( $row = fetch_row($result) ){
  if( 1 and 2 and 3 ){
    //SUCCESS
  }
  elseif( NOT 1 ){
    //1 is the problem
  }
  elseif( NOT 2 ){
    //2 is the problem
  }
  elseif( NOT 3 ){
    //3 is the problem
  }
}

1,2,3 are the condition (eg 1 = ($row['v'] == $k))

You'll have to figure out what to do about multiple rows, ideally the schema would prevent that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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