PHP确保唯一的用户名 [英] Php Ensuring a unique username

查看:58
本文介绍了PHP确保唯一的用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注册页面,我想确保用户名是唯一的.我已经在这里尝试了所有解决方案,但对我来说没有任何效果.

I have a register page and I want to ensure that usernames are unique. I have tried all the solutions on here already and nothing is working for me.

这是我当前遇到的错误:

This is the error I'm currently getting:

Warning:  mysqli_query() expects at least 2 parameters, 1 given 
in C:\xampp\htdocs\project\projectregistered.php on line 16
Query was empty

这是我的php:

 <?php
 $con=mysqli_connect("localhost","root","","test");
 // Check connection
 if (mysqli_connect_errno()) {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

$username = $_POST['username'];  

echo $username;

$query = mysqli_query("SELECT * FROM projectuser WHERE username='$username'");

$result1 = mysql_query($query) or die (mysql_error().$query);    
$count = mysql_num_rows($result1);

if ($count>0) {
echo 'Sorry! This Username already exists!';
} else {
    $surname = $_POST['surname'];
    $sql = "INSERT INTO projectuser (firstname, surname, username, password, location)
            VALUES
            ('$_POST[firstname]', '".mysql_real_escape_string($surname)."', '$_POST[username]', '$_POST[password]', '$_POST[location]')";
}

if (!mysqli_query($con,$sql)) {
    die('Error: ' . mysqli_error($con));
}
echo "1 record added ".$sql;

mysqli_close($con);

?>

推荐答案

在使用过程方法时,还需要将连接句柄作为第一个参数传递.应该是

As you're using the procedural approach, you also need to pass the connection handle as first argument. It should be

mysqli_query($con, "SELECT * FROM projectuser WHERE username='$username'");

此外,将数据库表中的username列设置为UNIQUE.

Additionally, make the username column in your DB table UNIQUE.

更新:
我刚刚意识到您同时使用了mysql_mysqli_函数.最好坚持第二个.因此您的代码应为:

Update:
I just realised you're using both mysql_ as well as mysqli_ functions. Better stick to the second one. So your code would be:

$query = "SELECT * FROM projectuser WHERE username='$username'";
$result = mysqli_query($con, $query);
$count = mysqli_num_rows($result);

但是如上所述,如果将username列设置为UNIQUE,则根本不需要进行检查.您可以在INSERT之后使用 mysqli_insert_id 进行检查是否已插入记录.如果尚未插入,则触发UNIQUE约束.这种方法比先SELECT仅检查用户名是否已经存在有效.

But as already mentioned above, if you set your username column as UNIQUE you won't need that check at all. You could use mysqli_insert_id after the INSERT to check whether a record has been inserted or not. IF it hasn't been inserted, then the UNIQUE constraint had fired off. This way is more efficient than SELECTing first just to check whether the username already exists.

这篇关于PHP确保唯一的用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆