doulandai0641 2014-06-16 09:51
浏览 33
已采纳

检查用户名/电子邮件是否可用方法 - PHP,PDO

I'm new in PHP. I try to make secure method that checks if username or email is not taken and I'm not sure if this is the right way. So my question is how can I do this better, or how would do it skilled programmer? Thanks a lot

private function checkAvailability() {
        try {
            $conn = new PDO(DB_SERVER, DB_USER, DB_PASS);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = ("SELECT COUNT(*) FROM users WHERE username = :username OR email = :email");
            $st = $conn->prepare($sql);
            $st->bindValue(":username", $_POST["username"], PDO::PARAM_STR);
            $st->bindValue(":email", $_POST["email"], PDO::PARAM_STR);
            $st->execute();
            if($st->fetchColumn() > 0) {
                $sql = ("SELECT COUNT(*) FROM users WHERE username = :username");
                $st = $conn->prepare($sql);
                $st->bindValue(":username", $_POST["username"], PDO::PARAM_STR);
                $st->execute();
                if($st->fetchColumn() > 0) {
                    throw new Exception("That username is already taken");
                } else {
                    throw new Exception("That e-mail is already registered.")
                }
                return 0;
            } else {
                return 1;
            }
            $conn = null;
        } catch (PDOException $e) {
            echo "Database error: " . $e->geMessage();
        } catch (Exception $e) {
            echo "Registration failed: " . $e->geMessage();
        }
    }

    public function registerUser() {
        if(self::checkAvailability) {
            // register user
        }
    }
  • 写回答

1条回答 默认 最新

  • dongxun4110 2014-06-16 09:57
    关注

    You are already on the right path here.

    The query SELECT COUNT(*) FROM users WHERE username = :username OR email = :email can be a performance problem, because the db can't use any index here. So you might want to split that in two statements one for username and one for email. That would also help you determining which error occured.

    Also you don't need every hit in the db just the first, so a limit 1 is also usefull.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制