使用PHP在while循环中插入数据(仅一次)

时间:2014-01-06 03:12:48

标签: php mysql

我有以下PHP代码:

<?php
    if(isset($_POST["tbn_submit"])){
        $userName = $_POST["text_username"];
        $pass = $_POST["text_password"];
        //$sql = "SELECT * FROM tbluser WHERE username='".$userName."' AND password='".$pass."'";
        $sql = "SELECT * FROM tbluser";
        $res = mysql_query($sql) or die(mysql_error());
        if(mysql_num_rows($res)>0){
            while($row= mysql_fetch_array($res)){
                $username=$row['username'];
                $userpas = $row['password'];
                $user_id=$row['userId'];
                $user_role=$row['possition'];
                $_SESSION['username'] = $username;
                $_SESSION['uid'] = $user_id;
                if($userName == $username && $pass == $userpas){
                    if($user_role=="Admin"){
                        echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';

                    }else{
                        echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
                    }
                }
                else if($userName == $username && $pass != $userpas){
                    echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
                }
                else if($userName != $username && $pass != $userpas){
//In this point I got insert multi time so I want it insert only 1 time to database
                    $query = "INSERT INTO tbluser(userId,username,password,possition,user_status) VALUES('','".$userName."','".$pass."','',1)";
                    $result = mysql_query($query) or die(mysql_error());
                    $id = mysql_insert_id();
                    if($result){
                        echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
                    }
                }
            }
        }else {
            echo "re";

        }
    }
?>

这是我的登录页面提交。当用户输入他们的用户名和密码时,如果用户名和密码已经在数据库中,它将在代码中测试某些情况,但如果用户名在数据库中但密码不匹配则应显示{{1 }}。

如果数据库中不存在用户名和密码,程序应创建用户名和密码并转到其他页面。我在最后一种情况下出错 - 我在数据库中插入了大量具有相同数据的记录。我知道这是因为我在代码中的while循环中编写了这些条目,但我不知道其他任何方式。如何使用单个记录填充数据库,而不是在wrong password.循环中写入重复的条目?

1 个答案:

答案 0 :(得分:2)

你的所有逻辑都错了:

  1. 无需检索所有用户以检查用户是否存在,
  2. tbluser应将username限制为UNIQUE,以避免重复的条目,
  3. 密码应该是哈希值,
  4. INSERT查询使用未转义的变量,
  5. 插入不匹配的用户名将导致错误存储在db,
  6. mysql_*系列函数已弃用
  7. 使用PDO

    登录用户

    <?php
    
    $dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
    
    if (isset($_POST["login"])) {
        $user = $_POST["username"];
        $pass = $_POST["password"];
    
        $statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
        $statement->bindParam(':user',$user);
        $statement->execute();
    
        /**
         * Returns FALSE in case nothing is found
         */
        $res = $statement->fetch(PDO::FETCH_ASSOC);
    
        if ($res) {
            $username = $res['username'];
            $password = $res['password'];
            $user_id = $res['userId'];
            $user_role = $res['possition'];
    
            if ($pass == $password) {
                $_SESSION['username'] = $username;
                $_SESSION['uid'] = $user_id;
    
                if ($user_role == "Admin") {
                    echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
                }
                else {
                    echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
                }
            }
            else {
                echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
            }
        }
        else {
            echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
        }
    }
    

    注册用户

    <?php
    
    $dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
    
    if (isset($_POST["register"])) {
        $user = $_POST["username"];
        $pass = $_POST["password"];
        $check = $_POST["passcheck"];
    
        $statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
        $statement->bindParam(':user',$user);
        $statement->execute();
    
        /**
         * Returns FALSE in case nothing is found
         */
        $res = $statement->fetch(PDO::FETCH_ASSOC);
    
        if ($res) {
            echo "<span style='text-align:center;color:red;'>Username exists.</span>";
        }
        else if ($pass != $check) {
            echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
        }
        else {
            $statement = $dbh->prepare("INSERT INTO tbluser (userId, username, password, position, user_status) VALUES ('', :user, :pass, '' , 1)");
            $statement->bindParam(':user',$user);
            $statement->bindParam(':pass',$pass);
            $statement->execute();
    
            echo "<span style='text-align:center;color:red;'>Username registered.</span>";
        }
    }
    

    使用mysql_query已弃用

    验证任何用户:

    <?php
    
    if (isset($_POST["login"])) {
        $user = $_POST["username"];
        $pass = $_POST["password"];
    
        /**
         * This line had the right idea!
         */
        $sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
        $res = mysql_query($sql) or die(mysql_error());
    
        if (mysql_num_rows($res) > 0) {
            $username = $row['username'];
            $password = $row['password'];
            $user_id = $row['userId'];
            $user_role = $row['possition'];
    
            if ($pass == $password) {
                $_SESSION['username'] = $username;
                $_SESSION['uid'] = $user_id;
    
                if ($user_role == "Admin") {
                    echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
                }
                else {
                    echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
                }
            }
            else {
                echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
            }
        }
        else {
            echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
        }
    }
    

    注册一些用户:

    <?php
    
    if (isset($_POST["register"])) {
        $user = $_POST["username"];
        $pass = $_POST["password"];
    
        /**
         * Ask the user to type its password twice
         */
        $check = $_POST["passcheck"];
    
        $sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
        $res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
    
        if (mysql_num_rows($res) > 0) {
            echo "<span style='text-align:center;color:red;'>Username exists.</span>";
        }
        else if ($pass != $check) {
            echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
        }
        else {
            $query = "INSERT INTO tbluser (userId, username, password, possition, user_status) VALUES ('','".mysql_real_escape_string($user)."','".mysql_real_escape_string($pass)."','',1)";
            $res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
            echo "<span style='text-align:center;color:red;'>Username registered.</span>";
        }
    }