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 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历