javascript php检查数据库中是否存在用户名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18244863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php check if a username exists in a database
提问by Some user
So I have a user form
registration, and what I am trying to do is: while a user is typing an email, the website will check my database if the email already has been used or not, before they hit the register button.
所以我有一个用户form
注册,我想要做的是:当用户输入电子邮件时,网站将在他们点击注册按钮之前检查我的数据库是否已使用该电子邮件。
The problem I'm having is that it won't check. It will only display "Searching in database". I just want to post my code so maybe someone can catch the error I'm making.
我遇到的问题是它不会检查。它只会显示“在数据库中搜索”。我只想发布我的代码,这样也许有人可以发现我犯的错误。
This is part of my registration page:
这是我的注册页面的一部分:
<tr class = "spacearound"> <!-- input for email address -->
<th>  Email: </th>
<td>
<input type = "text" id = "user_email" size = "50"
maxlength = "50" name = "u_email"
title = "Enter your email please"
onchange = "EmailCheck();"
onkeypress = "return InputLimiter(event, 'emailCharacters');"
/> *
<span id = "email_status"> </span>
</td>
<td><?php echo $message; ?></td>
</tr>
This is my JavaScriptfile, "checkusers.js":
这是我的JavaScript文件“checkusers.js”:
$('#user_email').keyup(function() {
var username = $(this).val();
$('#email_status').text('Searching database.');
if(username != ''){
$.post('checkemail.php',{ username: username }, function(data) {
$('#email_status').text(data);
});
} else {
$('#email_status').text('');
}
});
And this is my phpfile, where I check for an email, "checkemail.php":
这是我的php文件,我在其中检查电子邮件“checkemail.php”:
<?php
define('dbHost', 'xxxxx');
define('dbUser', 'xxxxx');
define('dbPassword', 'xxxxx');
define('dbName', 'xxxxx');
error_reporting(E_ALL ^ E_NOTICE);
$db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established ");
} //by now we have connection to the database
if(isset($_POST))['username'])){ //if we get the name succesfully
$username = mysqli_real_escape_string($db, $_POST['username']);
if (!empty($username)) {
$username_query = mysqli_query($db, "SELECT COUNT(`firstName`) FROM `users` WHERE `email`='$username'");
$username_result = mysqli_fetch_row($username_query);
if ($username_result[0] == '0') {
echo 'Email available!';
} else {
echo 'Sorry, the email '.$username.' is taken.';
}
}
}
?>
回答by kashimu
you have error here
你在这里有错误
if(isset($_POST))['username'])){
it should be
它应该是
if(isset($_POST['username'])){
$_POST['username']
should be enclosed inside isset function
$_POST['username']
应该包含在 isset 函数中