用于检查数据库“用户名已被占用”的php用户名

时间:2014-02-04 13:16:35

标签: php mysql forms

您好我有一个注册系统,它运作良好,我的问题是,如果已经根据我的数据库采取了如何检查用户名?我有这个脚本,它不会工作,有人可以帮我解决这个问题吗?

<?php

        if(empty($_POST['username'])){
          $username_error = "Please Input Username";
        }else{
          if( 6 > mb_strlen($_POST['username']) || 20 < mb_strlen($_POST['username'])){
            $username_error = "username must be at least 6 characters.";
          }else{
              $username = $_POST['username'];
              $sql = "SELECT
                    members.username
                    FROM
                    members
                    WHERE username = $username";
              $res = mysql_query($sql);
              if(mysql_num_rows($res)){
                $username_exists = "Username is already taken.";
              }else{
                $username = $_POST['username'];
              }
          }     
        }


?

问题在于else语句检查数据库是否采用了用户名。 请帮帮我,非常感谢

我收到此错误

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\TheSocioNet\stud_reg.php on line 210

1 个答案:

答案 0 :(得分:1)

请使用以下代码来解决您的问题

<?php

    if(empty($_POST['username'])){
      $username_error = "Please Input Username";
    }else{
      if( 6 > mb_strlen($_POST['username']) || 20 < mb_strlen($_POST['username'])){
        $username_error = "username must be at least 6 characters.";
      }else{
          $username = $_POST['username'];
          $sql = "SELECT
                members.username
                FROM
                members
                WHERE username = '". $username."'";
          $res = mysql_query($sql);
          if($res && mysql_num_rows($res) > 0){
            $username_exists = "Username is already taken.";
          }else{
            $username = $_POST['username'];
          }
      }     
    }