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 .

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看