dqwh1201 2015-12-04 14:54
浏览 34
已采纳

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

i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..

here my code

//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();
        }
    }
  • 写回答

1条回答 默认 最新

  • douzhuan1432 2015-12-04 15:09
    关注

    You can use the mysqli_num_rows() function to avoid data duplication in your database

    use this code :

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

    If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致