如何更改此脚本,以便当它发现MySQL数据库中存在用户时,它会更新并且不会返回错误消息?

时间:2014-05-09 12:25:44

标签: php mysql sql multiple-users

这部分脚本检查多个用户名,我希望它更新找到的用户而不是以用户存在的错误消息结束:

// Verify a users existance by username.  Function will fail if multiple usernames are encountered.
function userExists( $username ) 
{
    // set up prepared statement
    $stmt = $this->conn->prepare("SELECT * FROM $this->table WHERE $this->username_column = ?");

    // bind the parameters
    $stmt->bind_param("s", $username);

        // execute prepared statement 
    if(!$stmt->execute())
        {
            $this->lastError = "Error in ".__FUNCTION__.": Username provided has more then one (".$stmt->num_rows().") records associated with it where there should only be one record.";
            return false;
        }


    $stmt->store_result();

        // check to make sure a username doesn't have duplicate usernames
        if($stmt->num_rows() == 0)
        {
            $this->lastError = "Error in ".__FUNCTION__.": Username provided has more then one (".$stmt->num_rows().") records associated with it where there should only be one record.";
            return false;           
        }

        // return indicating success 
        return true; 
}

我不确定是否需要这个来帮助解答,但脚本的这一部分用于将新用户添加到数据库中:

function addUser( $username, $password ) 
{

    // encrypt password if set (default == enabled w/ sha1)
    if($this->use_encryption)
        $password = ($_SESSION['password']);
        $salt = "CHANGE-SALT"; 
        // Add some salt to the users password. 
        $salt .= $password; // The password is salted
        $password = $salt; // Change the password var to contain our new salted pass. 
        $password = md5($password);

    if($this->userExists( $username ))  
        die("ERROR USER EXISTS"); 


    // create sql   
    $sql = "INSERT INTO  $this->table ( $this->username_column , $this->password_column) VALUES (?, ?)";

    // set up prepared statement
    $stmt = $this->conn->prepare($sql);

    // bind the parameters
    $stmt->bind_param("ss", $username, $password);


     // execute prepared statement 
    if(!$stmt->execute())
        {
        $this->lastError = "Error in ".__FUNCTION__.": Supplied user/pass fields cannot be added.";
        return false;       
        }



    return true;
}       

非常感谢任何对此的帮助,提前谢谢。

特雷弗

1 个答案:

答案 0 :(得分:3)

  

REPLACE的工作原理与INSERT完全相同,只是如果在一个旧行中   table与PRIMARY KEY或UNIQUE的新行具有相同的值   index,在插入新行之前删除旧行。

将唯一索引添加到用户名列;

REPLACE INTO user SET username=".$username." AND password=".$password;

http://dev.mysql.com/doc/refman/5.5/en/replace.html