如何检查数据库中是否存在用户名?

时间:2017-02-26 22:08:37

标签: php mysql

我是PHP和MySQL的新手,我想问一下如何检查我的数据库中是否存在用户名?使用mysqli_num_rows检查我的变量$ userchecker和我的if语句。我知道这是错的,但我不知道如何做对。

if(isset($_POST['submit'])){
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        $username = mysqli_escape_string($con,$username);
        $password = mysqli_escape_string($con,$password);


        //Database connection
        $con = mysqli_connect('localhost','root','Jarious','register_and_login');
        $error = false;



        if (!$con) {
             die("Connection failed: " . mysqli_connect_error());
        }           

        $userchecker = mysqli_query($con,"SELECT * FROM users WHERE user_name = '$username'");


        if(empty($username) || mb_strlen($username) < 5){
            echo "Username is too short or empty." . '<br />';
            $error = true;

        }

        if(empty($password) || mb_strlen($password) < 5){
            echo 'Password is too short or empty. <br />';
            $error = true;
        }

        if(mysqli_num_rows($userchecker) > 1){
            echo 'Username is already taken.';
            $еrror = true;
        }

        if(!$error){
            $password = md5($password);
            $query = "INSERT INTO users(user_name,pass_word) VALUES ('$username', '$password')";
            $useradd = mysqli_query($con,$query);
        }

    }

2 个答案:

答案 0 :(得分:0)

你的代码非常庞大。所有想要在这里实现的东西都已在(PHP)框架中定义。显然,下面的SQL应该很容易做到。最初来自评论:

SELECT count(*) FROM users WHERE user_name = '$username'

答案 1 :(得分:-3)

<?
$n=$_POSTE['d1'];
$p=$_POSTE['t1'];


$c=mysql_connect('localhost','root','');
$b=mysql_select_db('lica');

$r1='SELECT * FORM user WHERE ($name='iheb')';
$r=mysql_query($r1);
if(mysql_num_rows($r)==0)
    echo'n''not existe ';
else
    echo 'exist';

我认为这项工作