如何防止PHP / mysql中重复的用户名 [英] How to prevent duplicate Usernames in php/mysql
问题描述
(这是我第一次使用php)
(This is my first try with php)
我有一个非常基本的注册页面。
http://graves-incorporated.com/test_sites/member_test/register /register.php
I have a very basic register page. http://graves-incorporated.com/test_sites/member_test/register/register.php
* 我刚刚记得PHP代码没有显示在源代码中,所以这里是: / p>
* I just remembered PHP code doesn't show up in the source so here it is:
enter code here
<?php
include('connection.php');
if(isset($_POST['form'])){
if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['conf_pass']) || empty($_POST['email'])){
echo '<b>Please fill out all fields.</b>';
}elseif($_POST['password'] != $_POST['conf_pass']){
echo '<b>Your Passwords do not match.</b>';
}else{
$url = 'http://graves-incorporated.com/test_sites/plantation_park_2012/';
echo '<META HTTP-EQUIV=Refresh CONTENT="2; URL='.$url.'">';
echo '<b>Congrats, You are now Registered.</b>';
mysql_query("INSERT INTO users VALUES(NULL, '$_POST[username]', '$_POST[password]', '$_POST[email]')");
}
}
?>
我想确保我不会在数据库中收到重复的用户和/或电子邮件地址。我在MySQL中为用户名和电子邮件设置了一个唯一键,这阻止了它,但实际表单中的用户并不知道,它仍然告诉他们恭喜你,你注册了或者说它是什么...哈哈
I want to make sure I don't get duplicate users and/or email addresses in the database. I set up a Unique Key in MySQL for Username and Email, which prevents it, but the user on the actual form doesn't know that, it still tells them "Congrats, you are signed up" or whatever it says... haha
那么我可以添加哪些PHP代码(代码中的哪里),以防止这种情况?
So what can I add to the php code (and where in the code) that would prevent this?
Dan Graves
Thanks for helping this major noob, Dan Graves
推荐答案
<?php
include('connection.php');
if(isset($_POST['form'])){
if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['conf_pass']) || empty($_POST['email'])){
echo '<b>Please fill out all fields.</b>';
}elseif($_POST['password'] != $_POST['conf_pass']){
echo '<b>Your Passwords do not match.</b>';
}else{
$dup = mysql_query("SELECT username FROM users WHERE username='".$_POST['username']."'");
if(mysql_num_rows($dup) >0){
echo '<b>username Already Used.</b>';
}
else{
$url = 'http://graves-incorporated.com/test_sites/plantation_park_2012/';
echo '<META HTTP-EQUIV=Refresh CONTENT="2; URL='.$url.'">';
$sql = mysql_query("INSERT INTO users VALUES(NULL, '$_POST[username]', '$_POST[password]', '$_POST[email]')");
if($sql){
echo '<b>Congrats, You are now Registered.</b>';
}
else{
echo '<b>Error Registeration.</b>';
}
}
}
}
?>
这篇关于如何防止PHP / mysql中重复的用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!