Bonjour,

Je suis face à un problème dont je ne trouve pas la solution.
En gros, je voudrais que si j'inscris l'utilisateur 'test' mais qu'il est déjà dans la BDD, alors il me retourne un message d'erreur, en théorie j'y arrive quand je n'utilise pas AJAX mais que du HTML / PHP , hors là ... c'est un peu différent.

Par rapport à mon fichier PHP, je ne sais pas trop ou placer ma requète ainsi que le IF pour l'identifiant.... mais surtout, est ce possible avec ce shéma de code PHP ?

Pourriez vous m'aider ?
Cordialement.

Voici le code PHP et AJAX:

<?php
include 'db/database.php';

    $array = array("identifiant" => "", "identifiantError" => "", "email" => "", "emailError" => "", "pass" => "", "passError" => "", "pass_confirm" => "", "pass_confirmError" => "", "isSuccess" => false);

    if ($_POST) 
    { 
        $array["identifiant"] = test_input($_POST["identifiant"]);
        $array["email"] = test_input($_POST["email"]);
        $array["pass"] = test_input($_POST["pass"]);
        $array["pass_confirm"] = test_input($_POST["pass_confirm"]);
        $array["isSuccess"] = true;
        $statut = 'membre';

        if (empty($array["identifiant"]))
        {
            $array["identifiantError"] = "Identifiant invalide";
            $array["isSuccess"] = false; 

        } 

        if (!isEmail($array["email"]))
        {
            $array["emailError"] = "E-mail invalide";
            $array["isSuccess"] = false; 
        }

        if (empty($array["pass"]) || $array["pass"] != $array["pass_confirm"])
        {
            $array["passError"] = "Les mots de passe ne correspondent pas";
            $array["isSuccess"] = false; 
        }

        if($array["isSuccess"]) 
        {
            $req = $db->prepare('INSERT INTO login (identifiant, email, pass, statut) VALUES (?,?,?,?)');
            $req->execute(array($_POST["identifiant"], $_POST["email"], $_POST["pass"], $statut));
        }

        echo json_encode($array);

    }

    function isEmail($email) 
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    function test_input($data) 
    {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }

?>
$(function () {

    $('#contact-form').submit(function(e) {
        e.preventDefault();
        $('.comments').empty();
        var postdata = $('#contact-form').serialize();

        $.ajax({
            type: 'POST',
            url: 'inscription-traitement.php',
            data: postdata,
            dataType: 'json',
            success: function(json) {

                if(json.isSuccess) 
                {
                    $('#success').fadeIn();
                    $('#contact-form')[0].reset();

                }
                else
                {
                    $('#identifiant + .comments').html(json.identifiantError);
                    $('#email + .comments').html(json.emailError);
                    $('#pass + .comments').html(json.passError);
                    $('#pass_confirm + .comments').html(json.passError);
                }                
            }
        });
    });

})

10 réponses


Bon j'ai un peu avancé, mais maintenant il me met que l'utilisateur existe quand le formulaire est posté..... mais ça enregistre bien dans la BDD.. sauriez vous pourquoi ?

j'ai corrigé le code au dessus avec ça:

        // REQUETE IDENTIFIANT DEJA PRIS
        $identifiantexist = $db->prepare('SELECT * FROM login WHERE identifiant = ?');
        $identifiantexist->execute(array($array['identifiant']));
        if (!empty($array["identifiant"]) AND $array["identifiant"] != !$identifiantexist->fetch()) {
            $array["identifiantError"] = "Cet utilisateur existe déjà";
            $array["isSuccess"] = false;
        }  

Bon je pense que cette fois c'est bon....
J'avais oublié dans mon IF le !empty après le AND... ça à l'air de marcher

        // REQUETE IDENTIFIANT DEJA PRIS
        $identifiantexist = $db->prepare('SELECT * FROM login WHERE identifiant = ?');
        $identifiantexist->execute(array($array['identifiant']));

                if (!empty($array["identifiant"]) AND !empty($array["identifiant"]) != !$identifiantexist->fetch()) {
            $array["identifiantError"] = "Cet utilisateur existe déjà";
            $array["isSuccess"] = false;
        }  

Ah ben non.... toujours le même problème, un idée ? :( je galère depuis 3heures

Pouquoi tu te compliques la vie
si ton utilisateur existe alors ta requête SELECT renvoie la ligne de l'utilisateur sinon le fetch renvoie false

if ( !$identifiantexist->fetch() ) {
    $array["identifiantError"] = "Cet utilisateur existe déjà";
    $array["isSuccess"] = false;
 }

Bonsoir, et merci de ta réponse, si je fais comme tu dis, quand je clique sur submit et ça dans tous les cas, il me retourne "cet utilisateur existe déjà...." et ne rentre plus rien dans la BDD.... je te remontre mon code PHP, ça se trouve je me suis trompé quelque part....

<?php
include 'db/database.php';

    $array = array("firstname" => "", "firstnameError" => "", "isSuccess" => false);
    // REQUETE IDENTIFIANT DEJA PRIS
    $identifiantexist = $db->prepare('SELECT * FROM connexion WHERE firstname = ?');
    $identifiantexist->execute(array($array['firstname']));

    if ($_SERVER["REQUEST_METHOD"] == "POST") 
    { 
        $array["firstname"] = test_input($_POST["firstname"]);
        $array["isSuccess"] = true; 

        if (empty($array["firstname"]))
        {
            $array["firstnameError"] = "Je veux connaitre ton prénom !";
            $array["isSuccess"] = false; 
        }

        if (!$identifiantexist->fetch() ) {
            $array["firstnameError"] = "Cet utilisateur existe déjà";
            $array["isSuccess"] = false;
         }

        if($array["isSuccess"]) 
        {
            $req = $db->prepare('INSERT INTO connexion (firstname) VALUES (?)');
            $req->execute(array($array["firstname"]));
        }

        echo json_encode($array);

    }

    function test_input($data) 
    {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }

?>

ton firstname est vide ?
comment le récupères-tu ?

j'ai ça pour dire que si le champ est vide, il m'affiche "je veux connaitre ton prénom"

    if (empty($array["firstname"]))
    {
        $array["firstnameError"] = "Je veux connaitre ton prénom !";
        $array["isSuccess"] = false; 
    }

Et en lisant la variable POST avant

$array["firstname"] = test_input($_POST["firstname"]);
// REQUETE IDENTIFIANT DEJA PRIS
    $identifiantexist = $db->prepare('SELECT * FROM connexion WHERE firstname = ?');
    $identifiantexist->execute(array($array['firstname']));

Je ne comprend pas bien ou tu veux en venir ?

Bonsoir.

Je ne comprend pas bien ou tu veux en venir ?

Ce que veut dire Huggy, c'est qu'avant de vouloir faire une requête SQL sur une variable, il faudrait d'abord qu'elle ne soit pas vide.
Sauf que toi tu ne la définie qu'après avoir fait la requête, il te faut donc d'abord définir la variable avant de l'utiliser pour ta requête SQL.
Soit comme ceci par exemple :

    if ($_SERVER["REQUEST_METHOD"] == "POST") 
    { 
        $array["firstname"] = test_input($_POST["firstname"]);
        $array["isSuccess"] = true;
        // REQUETE IDENTIFIANT
        $identifiantexist = $db->prepare('SELECT * FROM connexion WHERE firstname = ?');
        $identifiantexist->execute(array($array['firstname']));
    }