简体   繁体   中英

how to merge these two queries and adjust if else condition in mysql php

if($_SESSION['isstaff'] == 1){
    $qry1 = "select * from username where username ='".$_SESSION['username']."' and password='".$_SESSION['password']."' and status=1";
}else{
    $qry1 = "select * from pdetail where rollno =".$_SESSION['username']." and password='".$_SESSION['password']."' and remark=1";
}

fore.g.

select * from 
  if($_SESSION['isstaff'] == 1){username}else{pdetail} 
where username ='".$_SESSION['username']."' and  
      password='".$_SESSION['password']."' and 
      if($_SESSION['isstaff'] == 1){status=1}else{remark=1};

You will have to use case expression, check out for the documentation below:

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case

It will result somewhat like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

If I understand what you mean, you can do this using ternary operators in PHP:

//Determine if $isstaff is true or false
$isstaff = $_SESSION["isstaff"]==1 ? true : false;

$qry1 = "SELECT * FROM ".
    ($isstaff ? "`username` " : "`pdetail` ") . "WHERE ". //username or pdetail
    ($isstaff ? "`username` " : "`rollno` ") . " = '{$_SESSION['username']}' AND ". //username or rollno
    "`password` = '{$_SESSION['password']}' AND ".
    ($isstaff ? "`status` " : "`remark` ") . " = 1;"; //status or remark

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