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.

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测