doudao9915 2015-05-14 19:43
浏览 107
已采纳

为什么不检查用户是否存在?

I'm performing a query to check if a user exists before adding it to the database. If that result comes back then die and echo 'username already exists' but if it comes back empty then add the new user to the database.

For some reason it just adds a new user to the database anyway.

        //If post was 
        if (isset($_POST['submit'])) {

        // Check if username is blank
        if (!isset($_POST['username']) || empty($_POST['username'])) {
            echo "Username was blank<br />";
            die();
        } else {
            $username = mysqli_real_escape_string($connection, $_POST['username']);
        }

        // Check if password is blank
        if (!isset($_POST['password']) || empty($_POST['password'])) {
            echo "Password was blank<br />";
            die();
        } else {
            $password = mysqli_real_escape_string($connection, $_POST['password']);
            $password2 = md5($password);
            //echo $password;
        }

        // Check if email is blank
        if (!isset($_POST['email']) || empty($_POST['email'])) {
            echo "Email was blank<br />";
            die();
        } else {
            $email = mysqli_real_escape_string($connection, $_POST['email']);
            //$password = md5($password);
            //echo $password;
        }

        //Check to see if username alread exsists 
        $query_check = "SELECT * FROM users WHERE user = '$username' LIMIT 1";
        $result_check = mysqli_query($connection, $query_check);

         if(count(mysqli_fetch_array($result_check)) === 1) {
            echo "Username exists.";
            die();   

         } else {
                $query = "INSERT INTO users (user, pass, email) VALUES ('$username','$password2','$email');";
                $result = mysqli_query($connection, $query);
                if($result){  // returned TRUE, e.g. in case of a DELETE sql  
                    $_SESSION["username"] = $username;
                    header("Location: ../profile.php");

                } else { // returned FALSE
                    //echo "Error: " . mysqli_error($connection);
                    echo "Error during register <a href='../register.php'>Back To Register</a>";
                    die();
                }
         }



    } else {
        header("Location: ../index.php");
}
  • 写回答

2条回答 默认 最新

  • duanla3319 2015-05-15 01:23
    关注

    After taking a few minutes testing your code, found that you're using the wrong function.

    mysqli_fetch_array():

    Fetch a result row as an associative, a numeric array, or both

    You're trying to fetch an associative array.

    As opposed to mysqli_num_rows():

    Gets the number of rows in a result

    Replace (and which seems to have been taken from Félix's answer)

    if(count(mysqli_fetch_array($result_check)) === 1)
    

    with

    if(mysqli_num_rows($result_check) == 1)
    

    or

    if(mysqli_num_rows($result_check) > 0)
    

    Your original post contained:

    if(mysqli_fetch_array($result_check) === 1)
    

    which still stands to be the wrong method.


    if(mysqli_num_rows($result_check) >0) and make sure $username is defined. We don't know how/where if it is even defined.


    Now, if THAT fails, then your form element isn't named, and/or something else in your form is failing you.

    I.e.: <input type="text" name="username">


    Add error reporting to the top of your file(s) which will help find errors.

    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // rest of your code
    

    Sidenote: Error reporting should only be done in staging, and never production.


    Regarding using MD5.

    That isn't considered safe to use anymore, as far as password hashing goes.

    • That technology is old and is considered broken.

    For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.

    For PHP < 5.5 use the password_hash() compatibility pack.


    Pulled from ircmaxell's answer which uses PDO with prepared statements and password_hash():

    Just use a library. Seriously. They exist for a reason.

    Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.

    $dbh = new PDO(...);
    
    $username = $_POST["username"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $hash = password_hash($password, PASSWORD_DEFAULT);
    
    $stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
    $stmt->execute([$username, $email, $hash]);
    

    And on login:

    $sql = "SELECT * FROM users WHERE username = ?";
    $stmt = $dbh->prepare($sql);
    $result = $stmt->execute([$_POST['username']]);
    $users = $result->fetchAll();
    if (isset($users[0]) {
        if (password_verify($_POST['password'], $users[0]->password) {
            // valid login
        } else {
            // invalid password
        }
    } else {
        // invalid username
    }
    

    Footnotes:

    I noticed you are using headers.

    You should add exit; after each header. Otherwise, your code may want to continue executing.

    header("Location: ../profile.php");
        exit;
    

    and do the same for the other one also.

    You're also using sessions. session_start(); isn't present in your posted and will fail if it isn't included; an insight.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题