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

标签 php html mysql

我从昨天开始就一直在尝试,几乎在 Stackoverflow 和谷歌搜索中涵盖了有关此事的所有问题,但到目前为止没有任何效果对我有用,我尝试在更新数据库中的用户名之前检查用户名可用性,但是,它不会检查并且始终直接更新用户名,而不会出现有关名称不可用的错误消息..

这是我的代码

//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,则用户名已存在于您的数据库表中。所以在这种情况下会抛出错误。 else INSERT 将用户名插入数据库并显示成功消息。

关于php - 检查数据库中的用户名并更新[html,mysql,php],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091075/

相关文章:

mysql - 返回 mysql 所在的所有行

PHP PDO Mysql 插入失败,不抛出异常或错误

php - 调试 zip 存档和下载

phpstorm 生成带有类型提示的 setter

html - 按钮文本与查询字符串中提交的值不同

PHP 检查用户是否存在 PDO

mysql - 映射成功后 sqoop 导出失败

php - 当我尝试打开 phpmyadmin 时出现错误 403。我该怎么做才能纠正它?

jquery - 输入标签应该适契约(Contract)一行而不是第二行CSS问题

javascript - beginPath() 和 closePath() 究竟做了什么?