Php 用户类在数据库中不将重复电子邮件返回为false
我创建了一个user类,它验证通过表单传递的数据,然后更新数据库表users。我想添加额外的功能,例如检查表中是否存在用户名和电子邮件,我已经从stackoverflow的成员那里获得了一些帮助,以便开始构建此功能,但是下面的代码仍然允许将重复的电子邮件插入数据库,我没有收到任何sql错误消息,只收到一条成功消息,如下所示“插入1行”。显然,我希望收到错误消息“email exists” 任何帮助都会有帮助Php 用户类在数据库中不将重复电子邮件返回为false,php,mysqli,prepared-statement,Php,Mysqli,Prepared Statement,我创建了一个user类,它验证通过表单传递的数据,然后更新数据库表users。我想添加额外的功能,例如检查表中是否存在用户名和电子邮件,我已经从stackoverflow的成员那里获得了一些帮助,以便开始构建此功能,但是下面的代码仍然允许将重复的电子邮件插入数据库,我没有收到任何sql错误消息,只收到一条成功消息,如下所示“插入1行”。显然,我希望收到错误消息“email exists” 任何帮助都会有帮助 public function insert() { $result = $this-
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代码-----------------
之后您需要调用
fetch
:
$result->bind_result($email_count);
$result->close();
$result->fetch();//fecth
$result->close();
//then
if ($email_count > 0) {
echo "email exisits!";
}
注意,对于准备好的语句,不需要使用real\u escape\u string
@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";
}
$result->bind_result($email_count);
$result->close();
$result->fetch();//fecth
$result->close();
//then
if ($email_count > 0) {
echo "email exisits!";
}