0

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

// 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;
}       

对此的任何帮助将不胜感激,在此先感谢。

特雷弗

4

1 回答 1

3

REPLACE 的工作方式与 INSERT 完全相同,只是如果表中的旧行与 PRIMARY KEY 或 UNIQUE 索引的新行具有相同的值,则在插入新行之前删除旧行。

为用户名列添加唯一索引;

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

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

于 2014-05-09T12:32:08.560 回答