duansao6776 2013-03-01 17:38
浏览 11
已采纳

如何缩短功能查询?

hello i have this function:

function mail_exists($email){
    global $db;
    $email = sanitize($email);
    $query = $db->query("SELECT Email FROM table1 WHERE Email= '$email' ");
    $check = $query->num_rows;
    $query2 = $db->query("SELECT Email FROM table2 WHERE Email= '$email' ");
    $check2 = $query->num_rows;
    return ($check > 0 || $check2 > 0) ? true : false;
}

first of all i would like to know how i can shorten it by using only one query and second thing is, why this does not work when using two queries? both tables have a different structure. in table1 the field email is no. 16 and on table2 it is field no.6.

thanks alot.

  • 写回答

3条回答 默认 最新

  • duanguanzai6181 2013-03-01 17:47
    关注

    First of all you made a logic error *here in the last lines: $query->num_rows; should be: $query2->num_rows; and then resulting into:

    function mail_exists($email){
        global $db;
        $email = sanitize($email);
        $query = $db->query("SELECT Email FROM table1 WHERE Email= '$email' ");
        $check = $query->num_rows;
        $query2 = $db->query("SELECT Email FROM table2 WHERE Email= '$email' ");
        $check2 = $query2->num_rows; // *here
        return ($check > 0 || $check2 > 0) ? true : false;
    }
    

    Second, you should be using two different queries if you are dealing with two completely different contexts. Don't join queries when you don't need to. If you are just counting rows you can easily do:

    function mail_exists($email){
        global $db;
        $email = sanitize($email);
        $query = $db->query("SELECT COUNT(*) FROM table1 WHERE Email= '$email' ");
        $query2 = $db->query("SELECT COUNT(*) FROM table2 WHERE Email= '$email' ");
        $count1 = $query->fetch_row();
        $count2 = $query2->fetch_row();
        return ($count1[0] || $count2[0]);
    }
    

    The SQL COUNT() function is there to give you the most performant way to count rows.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能