繁体   English   中英

检查数据库中的用户名并更新[html,mysql,php]

[英]check username in databse and update[html,mysql,php]

我从昨天开始一直在尝试,并且几乎在Stackoverflow和Google搜索中涵盖了有关此问题的所有问题,但是到目前为止,没有任何工作与我合作,我尝试在更新数据库中的用户名之前检查用户名的可用性,但是,它不会进行检查并且始终会更新用户名直接显示,没有关于名称不可用的错误消息。

这是我的代码

//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
    echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['clientN'])) {
        $query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
        if (mysqli_num_rows($query) != 0) {
            echo "<script>
alert('Username is not available, please select another username.');
</script>";
            header('Location: '. $_SERVER['HTTP_REFERER']  );
        } else {
            // run sql 
            $sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
            if ($con->query($sql) === TRUE) {
                echo "<h3> New record created successfully</h3>";
                header('Location: '. $_SERVER['HTTP_REFERER']  );
            } else {
                echo "Error : " . $sql  . "<br>" . $con->error;
            }
            $con->close();
        }
    }

您可以使用mysqli_num_rows()函数来避免数据库中的数据重复

使用此代码:

//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];    

$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query

$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists

if( $num_row > 0)
{
    // display 'username exists error'
}
else
{
   // Insert user name into your database table
}

如果num_rows大于0,则用户名已经存在于数据库表中。 所以在那种情况下抛出错误。 否则INSERT用户名到你的数据库,并显示成功消息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM