-1

I am currently trying to create a registration form. I have a small problem with the condition that allows me to know if the mail that the user enters, exists or not in my database

Adding the user works fine but when I re-enter the same mail, it is added to the database while it will not have to because the mail already exists

Here is my code:

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();}

Guest's table on my phpmyadmin

PSZWK
  • 3
  • 1
  • 3
  • 4
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Mar 06 '17 at 14:14
  • 1
    Is `$result = $query->fetch(PDO::FETCH_OBJ);` really empty? – JustBaron Mar 06 '17 at 14:14
  • http://stackoverflow.com/questions/15287011/phppdo-how-to-check-if-email-is-already-registered – Shafiqul Islam Mar 06 '17 at 14:16
  • I think your select query having some negligible syntax error..first test that query directly in the database..and go ahead.. – Janen R Mar 06 '17 at 14:20
  • @JayBlanchard Yes I know that at the moment my database is not secure because at the moment I am not yet at this level. This is a bogus database so I can train;) – PSZWK Mar 07 '17 at 00:11

3 Answers3

0

You have two "fetch" therefore I suppose the second one is empty ;)

glefait
  • 1,651
  • 1
  • 13
  • 11
0

I didn't test it yet but I think you did many fetch there which is wrong for me.

Should be something like this:

$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
}
Đào Minh Hạt
  • 2,742
  • 16
  • 20
0

You can make function to check if the email exists before entering it into database

function emailExist($email) {
    $db = new PDO($connectionString, $conf['login'], $conf['password']);

    $query = $db->prepare("SELECT email FROM users WHERE email = :email");
    $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 */
}

But don't forget to take care of the scope variables inside the function

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ali Sadran
  • 264
  • 2
  • 4
  • Basically, if I understand correctly, before try {} catch {} I have an emailExist function? And that I must put my try {} catch {} in the if – PSZWK Mar 06 '17 at 23:03
  • you can put your try{} catch block first and then call the $db variable inside the function as global $db; and then call the function. – Ali Sadran Mar 07 '17 at 17:21