如何编写多堆查询的条件,如

时间:2017-01-18 18:16:29

标签: php mysql if-statement or-condition

我有3个问题,比如

$q1 = select email from tbl students
$q2 = select email from tbl corporates
$q3 = select email from tbl institutes

如果所有上面的电子邮件数量为零,我想检查所有3个表格然后只进行那样的操作,  我可以这样写:

if(mysqli_num_rows($q1) || mysqli_num_rows($q2)  || mysqli_num_rows($q3) ==0){
proceed to process. 
}else{
do nothing
}

我的问题是,这是一种正确的接近方式,或者我需要学习更好的东西。

3 个答案:

答案 0 :(得分:1)

你需要使用&而不是||并检查每个mysql对象的行数

if(mysqli_num_rows($q1) == 0 && mysqli_num_rows($q2) == 0 && mysqli_num_rows($q3) ==0){
    //proceed to process. 
} else {
    //do nothing
}

答案 1 :(得分:1)

您应首先执行这些查询,以便:

$db = mysqli_connect("localhost","my_user","my_password","my_db");
$q1 = "select email from tbl students";
$q2 = "select email from tbl corporates";
$q3 = "select email from tbl institutes";

$db_q1 = mysqli_query($db, $q1);
$db_q2 = mysqli_query($db, $q2);
$db_q3 = mysqli_query($db, $q3);

if(mysqli_num_rows($db_q1) == 0 && mysqli_num_rows($db_q2) == 0 && mysqli_num_rows($db_q3) == 0) {
proceed to process. 
}

答案 2 :(得分:1)

尝试使用mysqli_multi_query()

可以更轻松

$con=mysqli_connect("localhost","my_user","my_password","my_db");// Check connection

if (mysqli_connect_errno()) {

  echo "Failed to connect to MySQL: " . mysqli_connect_error();   

}

$sql = select email from tbl students";
$sql .= select email from tbl corporates";
$sql .= "select email from tbl institutes";   

// Execute multi query   

if (mysqli_multi_query($con,$sql)){     

do{   // Store first result set   

    if ($result=mysqli_store_result($con)) {  // Fetch one and one row

       if (mysqli_fetch_row($result) == 0)  {    

           //your code here
    }  
 }  

}