dtwk6019 2014-12-19 20:57
浏览 39
已采纳

尝试在用户名存在时弹出错误

I have seen many articles on this same question and have been unable to translate their answer to my problem. Basically i made my field 'username' unique in my database and would like to catch an the error of existing username in databse and echo something else out more user friendly. As of now i am able to get the error message but unable to control it. I simply want to let the user know when the username already exist in the database. Any help would be greatly appreciated.

This is the error i get when adding a member with a already used 'username'.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'theller' for key 'username'' in /Applications/MAMP/htdocs/TESTING/PHP/PHP-TEST/addMember.php:42 Stack trace: #0 /Applications/MAMP/htdocs/TESTING/PHP/PHP-TEST/addMember.php(42): PDOStatement->execute(Array) #1 {main} thrown in /Applications/MAMP/htdocs/TESTING/PHP/PHP-TEST/addMember.php on line 42

here is my script that is called when my ajax script executes and send over its data.

<?php ob_start();
          require_once 'classes/Config.php';
          try {
              $conn = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
              $data = $conn->query('SELECT * FROM Testing');
          } catch(PDOException $e) {
                if(($PDO->errorCode() == 23000) || ($PDOStatement->errorCode() == 23000)) {
                  echo 'USER ALREADY EXIST';
                } 
                else {
                 // not a dupe key rethrow error
                 echo 'error';
                }
            }


        $form = $_POST;
        $firstname = htmlspecialchars($form[ 'firstname' ]);
        $lastname = htmlspecialchars($form[ 'lastname' ]);
        $username = htmlspecialchars($form[ 'username' ]);
        $password = htmlspecialchars($form[ 'password' ]);
        $passMatch = htmlspecialchars($form[ 'pass_match' ]);
        $message = htmlspecialchars($form[ 'message' ]);
        $email = htmlspecialchars($form[ 'email' ]);

        if (empty($firstname) || empty($lastname) || empty($username) || empty($password)|| empty($passMatch)|| empty($message)|| empty($email)){
            $error = "Complete all fields";
        }
        // Password match
        if ($password != $passMatch){
            $error = "Passwords don't match";
        }
        // Email validation
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
            $error = "Enter a  valid email";
        }
        if(IsInjected($email)) {
            $error = "Bad email value!";
        }
        if(!isset($error)){
            $sql = "INSERT INTO Testing ( firstname, lastname, message, email, username, password ) VALUES( :firstname, :lastname, :message, :email, :username, :password )";
            $query = $conn->prepare( $sql );
            $query->execute( array( ':firstname'=>$firstname, ':lastname'=>$lastname, ':message'=>$message, ':email'=>$email, ':username'=>$username, ':password'=>$password ));
            if(!$query->rowCount() > 0){
                echo "exists! cannot insert";
            }else{
            header('Location: thankyou.php'); 
            }

        }
        else{
            echo "error occured: ".$error;
            exit();
        }
?>
  • 写回答

1条回答 默认 最新

  • dounang1974 2014-12-19 21:14
    关注

    I had similar problem in my recent project. Please try to replace your catch statement with the following:

    catch(PDOException $e) {
        if(isset($conn))
        {
            if($conn->errorInfo()[0] == 23000) {
                echo 'USER ALREADY EXIST';
            } 
            else {
            // not a dupe key rethrow error
                echo 'error';
            }
        }
    }
    

    Information about SQLSTATE error resides in an errorInfo array of the PDO object used for the query

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

报告相同问题?

悬赏问题

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