簡體   English   中英

如何更改此腳本,以便當它發現MySQL數據庫中存在用戶時會更新並不返回錯誤消息?

[英]How do I change this script so when it finds a user exists in a MySQL database it updates and doesn't return the error message?

腳本的此部分檢查多個用戶名,我希望它更新找到的用戶,而不是以用戶存在的錯誤消息結尾:

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

非常感謝您,為此提供的任何幫助。

特雷弗

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM