我创建了一个用户类,它验证通过表单传递的数据,然后更新数据库表用户。我想添加额外的功能,例如检查用户名和电子邮件是否存在于表中,我已经从 stackoverflow 的成员那里获得了一些帮助才能开始构建它,但是下面的代码仍然允许将重复的电子邮件插入到数据库,我没有收到任何 sql 错误消息,只是成功消息如下“插入了 1 行”。显然我期望错误消息“电子邮件存在”
任何帮助都会有所帮助。
public function insert() {
$result = $this->mysqli->prepare("SELECT COUNT(*) FROM users WHERE email=?");
$result->bind_param("s", $_POST['email']);
$result->execute();
$result->bind_result($email_count);
$result->close();
if ($email_count > 0) {
echo "email exisits!";
} else {
//escape the POST data for added protection
$username = isset($_POST['username']) ? $this->mysqli->real_escape_string($_POST['username']) : '';
$cryptedPassword = crypt($_POST['password']);
$password = $this->mysqli->real_escape_string($cryptedPassword);
$name = isset($_POST['name']) ? $this->mysqli->real_escape_string($_POST['name']) : '';
$email = isset($_POST['email']) ? $this->mysqli->real_escape_string($_POST['email']) : '';
$stmt = $this->mysqli->prepare("INSERT INTO users (username, password, name, email) VALUES (?, ?, ?, ?)");
//var_dump($this->mysqli->error);
$stmt->bind_param('ssss', $username, $password, $name, $email); // bind strings to the paramater
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
} // end email_count and insert to table
} // end function
我已经使用了下面附加的这个 ajax 代码,它对我有用....试试它是否有帮助....
ajax代码-----
<script type="text/javascript">
$(document).ready(function() {
// check username availability on focus lost
$('#username').focusout(function() {
if ($('#username').val()!='') {
var username=$('#username').val();
$.ajax({
url: "/gtlqa/checkUserNameAvailability/checkAvailability.html?username="+username,
method:'GET',
success:function(data){
if(data!="available")
{
$('input:submit').attr("disabled", true);
$("#usernameErrorMessage").html("username already exists");
}
else
{
$("#usernameErrorMessage").html("available");
$('input:submit').attr("disabled", false);
}
}
});
}
});
});
function checkAvailability() {
$.getJSON("/checkUserNameAvailability", {
username : $('#username').val()
}, function(available) {
if (available) {
fieldValidated("username", {valid : true});
$('input:submit').attr("disabled", false);
} else {
$('input:submit').attr("disabled", true);
fieldValidated("username", {valid : false, message : $('#username').val() + " is not available"});
}
});
}
</script>
控制器 - - - - - - - -
@RequestMapping(value="checkAvailability",method = RequestMethod.GET)
public @ResponseBody String getAvailability(@RequestParam("username") String username) {
System.out.println("username is"+username);
boolean status=userService.available(username);
if(status)
{
return "available";
}
else
return "username already exists";
}