我目前正在尝试创建注册表单。我的条件有一个小问题,让我知道用户输入的邮件,是否存在于我的数据库中
添加用户工作正常,但是当我重新输入相同的邮件时,它会被添加到数据库中,而不会因为邮件已经存在而被添加到数据库中
这是我的代码:
JS AJAX:
$('#btn_submit').click(function() {
/* Action on the event */
//1. Récupération des données saisie dans les champs du formulaire
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var phone = $('#phone').val();
var email = $('#email').val();
// var fullValues = firstname + " - " + lastname + " - " + email + " - " + phone + " - " + adress + " - " + country;
// alert(fullValues);
//2. Appel Ajax pour envoyé et traité les données en méthod GUEST vers le fichier manageGuest.php
$.ajax({
data:{
firstname: firstname,
lastname: lastname,
phone: phone,
email: email
},
url: '/core/manageGuest.php',
dataType: 'text',
type: 'GET',
success:function(response){
console.log("Email not Found ! Compte Created");
},
error:function(response){
console.log("Email Found ! Try Again ");
}
})
});
PHP:
$conf= Conf::$databases['default'];
$connectionString= "mysql:host=". $conf['host'] .";dbname=". $conf['database'];
try {
/* 1. Connection à la base de donnée */
$db = new PDO($connectionString, $conf['login'], $conf['password']);
//set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$lastname = $_GET['lastname'];
$firstname = $_GET['firstname'];
$email = $_GET['email'];
$tel = $_GET['phone'];
/* 2. verification si l'email existe dans la BDD*/
$query = $db->prepare("SELECT email
FROM guest
WHERE email=:email");
$query->execute(array('email'=>$email));
$query->fetch(PDO::FETCH_OBJ);
$result = $query->fetch(PDO::FETCH_OBJ);
if(empty($result)){
$query = $db->prepare("INSERT INTO guest (firstname, lastname , tel, email)
VALUES('$firstname','$lastname', '$tel', '$email')");
$query->execute();
echo "Le compte été créé";
} else {
echo "Cette email existe déjà";
}}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();}
答案 0 :(得分:0)
你有两个&#34; fetch&#34;因此我想第二个是空的;)
答案 1 :(得分:0)
我还没有对它进行测试,但我认为你在那里做了很多取错,这对我来说是错误的。
应该是这样的:
$query = $db->prepare("SELECT email
FROM guest
WHERE email=:email");
$query->execute(array('email'=>$email));
if ($query->rowCount() > 0) {
// There is exist record
} else {
// Insert new record
}
答案 2 :(得分:0)
您可以在输入数据库
之前创建电子邮件以检查电子邮件是否存在function emailExist($email)
{
$db = new PDO($connectionString, $conf['login'], $conf['password']);
$sql = "SELECT email FROM users WHERE email = :email";
$query = $db->prepare($sql);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() == 1) {
return true;
} else {
return false;
}
}
if(emailExist($email)) {
/* do something */
} else {
/*register the user */
}
但不要忘记在函数
中注意范围变量