PDO在登录时获取用户的数据库值并将其存储到$ _SESSION

时间:2014-10-17 22:37:40

标签: php mysql session pdo

我现在已经开展了好几天的工作,但却无法对其进行排序。我有一个注册表和一个logi表。我想要做的就是在他登录时保存检索用户的数据,并在会话激活时保存。这是我最近的尝试 这是我的题词.php(注册部分)

<?php //script pour vérifier et enregistrer les données
            ini_set('display_errors',1); 
            if (isset($_POST['submit']))
            {
                //on récupère les données entrées
                $name = ucfirst($_POST['userName']); //mettre le premier caractère en majuscule
                $firstName = ucfirst($_POST['firstName']);
                $birthDate = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
                $languageM = $_POST['langueM']; //langue maternelle
                $languageE = $_POST['langueE']; //langue étudiée
                $niveau = $_POST['level'];//niveau première langue étudiée
                $langueAjoutee = $_POST['secondeLangue'];
                $niveau2 = $_POST['level2'];
                $email =  $_POST['mailInput'].'@'.$_POST['schools'];
                $password1 = $_POST['password1'];
                $password2 = $_POST['password2'];

                if(isset($name,$firstName,$birthDate,$languageM,$languageE,$niveau,$email,$password1,$password2))
                {

                    if ($password1===$password2)
                    {
                        //hashage du mot de passe
                        $password1_sha1 = sha1($password1);
                        $password2_sha1 = sha1($password2);
                        // si utilisateur déjà enregistré
                        $bdd = new PDO('mysql:host=localhost;dbname=bladuo', 'root', '');
                        $bdd->exec('SET NAMES utf8');//affichage caractères utf-8 dans la bdd
                        $stmt= $bdd->prepare("SELECT COUNT(*) AS count FROM `membres` WHERE email=?");
                        $stmt->execute(array($email));
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
                        {
                            $email_count = $row["count"];
                        }
                        //if email already used

                        else
                        {
                        //check password length 

                            else
                            {   
                             //connection à la bdd
                                try
                                {
                                    $bdd = new PDO('mysql:host=localhost;dbname=bladuo', 'root', '');
                                    $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                                    $bdd->exec('SET NAMES utf8');//affichage caractères utf-8 dans la bdd



                                    //enregistrement de l'étudiant dans la bdd
                                    $stmt =  $bdd->prepare('INSERT INTO                                                                                                                                                                                                                                                                              members(nom,prenom,date_de_naissance,langue_maternelle,langue_etudiee,niveau,langu2,niveau2,email,passe)
                                           VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?,?)');
                                    $success = $stmt->execute(array($name , $firstName , $birthDate, $languageM ,                                                                         $languageE,$niveau,$langueAjoutee,$niveau2,$email,$password1_sha1)); 

                                    if($success)//si l'utilisateur est enregistré dans la bdd
                                    {   
                                        header('Location: Index.php');
                                    }else

                                    {    
                                       echo "INSERT a echouer!!";
                                       exit();
                                    }
                                }
                                catch(Exception $e)
                                {
                                    die('Erreur : '.$e->getMessage());
                                } 
                            }

                        }

                    }else 
                    {
                        print "<span style=\"color:red;\">Les mots de passe ne sont pas identiques</span>";
                        exit();
                    }

                    }else
                    {
                        print "<span style=\"color:red;\">une des variables n'est pas attribuée</span>";
                    }          

            }
        ?>

和我的reg.php(登录表单)

<?php 
ini_set('display_errors',1); 
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
$errmsg_arr = array();
$errflag = false;

    // connexion db
   $bdd = new PDO('mysql:host=localhost;dbname=bladuo', 'root', '');
   $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // nouvelle donnée
    $mail = $_POST['mail'];
    $password = $_POST['pwd'];
    $password_sha =sha1($password);
    if($mail == '') {
        $errmsg_arr[] = 'Veuillez entrer votre addresse email';
        $errflag = true;
    }
    if($password == '') {
        $errmsg_arr[] = 'Veuillez entrer votre mot de passe';
        $errflag = true;
    }

    // query
    $result = $bdd->prepare("SELECT * FROM members WHERE email=? AND passe=?");
    $result->bindParam(1,$mail);
    $result->bindParam(2,$password_sha);
    $result->execute();
    $rows = $result->fetch(PDO::FETCH_NUM);
    print_r($rows);
    if($result->rowCount() == 1) 
    { 
       $getUsers = $bdd->prepare("SELECT * FROM members WHERE nom=? AND email=?");
       $getUsers->bindParam(1,$name);
       $getUsers->bindParam(2,$email);
       $getUsers->execute();
       $users = $getUsers->fetch();
       print_r($users);
       while($user = $getUsers->fetch(PDO::FETCH_NUM)){
        $_SESSION['nom']=$users['nom'];
        $_SESSION['email']=$users['email'];
       }
    $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
       header("location: Accueil.php"); 
    } else 
    {
        $errmsg_arr[] = "Email ou mot de passe incorrecte ou vide"; 
        $errflag = true; 
    }
    if($errflag) {
        $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        session_write_close();
        header("location: Index.php");
        exit();
    }

&GT;

感谢任何帮助

3 个答案:

答案 0 :(得分:1)

除了确保您的变量按照@ Kypros的建议正确传递到此页面之外,还可以尝试使用类系统。

用户类

<?php
    class SetUserInfo
        {
            // Database connection
            public  $db;
            // Error reporting
            public  $error;
            // Set to check pass1 = pass 2
            public  $passCheck;
            // Storage for user submission data
            public  $useInfo;

            protected   $host       =   'localhost';
            protected   $database   =   'dbname';
            protected   $user       =   'username';
            protected   $pass       =   'password';

            public  function __construct()
                {
                    // Save db connection
                    $this->db   =   new DBEngine($this->host,$this->database,$this->user,$this->pass);
                }

            // This method pulls user from system
            public  function FetchUser($pass, $email)
                {
                    // If the email address is valid, fetch from db
                    if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $info   =   $this->db->prepare("SELECT * FROM members WHERE passe=? AND email=?");
                            $info->bindParam(1,$pass);
                            $info->bindParam(2,$email);
                            $info->execute();
                            // If there are rows, set them to an array
                            if($info->rowCount() == 1) {
                                    $user   =   $info->fetch(PDO::FETCH_ASSOC);
                                }
                        }

                    // Return the user array if validated or else return false/0
                    return (isset($user))? $user:0;
                }

            // This should return the count
            public  function EmailCount()
                {
                    // Assign email from previously assigned email [ from Process() array ]
                    $query  =   $this->db->con->prepare("SELECT COUNT(*) AS count FROM `members` WHERE email=?");
                    $query->execute(array($this->useInfo['email']));

                    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
                            $count = $row["count"];
                        }

                    if(isset($count) && $count == 1)
                        $this->error['email']['available']  =   'Compte d\'utilisateur déjà dans le système';

                    return (isset($count) && $count == 1)? 1:0;
                }

            public  function CreateRegistration($errors = false)
                {
                //  print_r($this->useInfo);

                    $this->db->con->exec('SET NAMES utf8');
                    //enregistrement de l'étudiant dans la bdd
                    $query = $this->db->con->prepare('INSERT INTO                                                                                                            members (nom,prenom,date_de_naissance,langue_maternelle,langue_etudiee,niveau,langu2,niveau2,email,passe) 
                    VALUES(?,?,?,?,?,?,?,?,?,?)');

                    $query->bindParam(1,$this->useInfo['name']);
                    $query->bindParam(2,$this->useInfo['firstName']);
                    $query->bindParam(3,$this->useInfo['birthDate']);
                    $query->bindParam(4,$this->useInfo['languageM']);
                    $query->bindParam(5,$this->useInfo['languageE']);
                    $query->bindParam(6,$this->useInfo['niveau']);
                    $query->bindParam(7,$this->useInfo['langueAjoutee']);
                    $query->bindParam(8,$this->useInfo['niveau2']);
                    $query->bindParam(9,$this->useInfo['email']);
                    $query->bindParam(10,$this->useInfo['passe']);
                    $query->execute();

                    // Validate user right.
                    $user   =   $this->ValidateLogin($this->useInfo['email'],$this->useInfo['passe'],0);

                    // Toggle error reporting on and off. Default is off.
                    if($errors == true || $errors == 1) { ?>
                        <pre>
                        <?php
                        // Print sql error
                        print_r($query->errorInfo());
                        // Print all values set to be inserted
                        print_r($this->useInfo);
                        // Print post
                        print_r($_POST); ?>
                        </pre>
                        <?php }

                    // Send back success or failure
                    return (is_array($user))? 1:0;
                }

            public  $loginVars;
            public  function ValidateLogin($email = '',$password = '',$validate=1)
                {
                    // Check that email is valid
                    $this->loginVars['mail']    =   (isset($email) && filter_var($email, FILTER_VALIDATE_EMAIL))? $email:0;
                    // Check that password is not empty
                    $this->loginVars['pwd']     =   (isset($password) && !empty($password))? $password:0;

                    // If there are no problems check database
                    if(!in_array('0',$this->loginVars)) {

                            // Assign encryption or process raw (could registration has encrytion alredy)
                            $this->loginVars['password_sha']    =   ($validate == 1)? sha1($this->loginVars['pwd']):$this->loginVars['pwd'];
                            // Prepare to check db
                            $query                              =   $this->db->con->prepare("SELECT * FROM `members` WHERE email=? AND passe=?");
                            $query->bindParam(1,$this->loginVars['mail']);
                            $query->bindParam(2,$this->loginVars['password_sha']);

                            // Execute search
                            $query->execute();

                            // If there are returned rows (1 specifically) set to array
                            if($query->rowCount() == 1) {
                                    $rows   =   $query->fetch(PDO::FETCH_ASSOC);
                                    return $rows;
                                }
                            else {
                                    $this->error['login']['error']  =   'Échec de la connexion.';
                                    return 0;
                                }
                        }
                    else {
                            if($this->loginVars['email'] == 0)
                                $this->error['invalid']['email']    =   'Veuillez entrer votre addresse email';
                            if($this->loginVars['pwd'] == 0)
                                $this->error['invalid']['pwd']    =   'Veuillez entrer votre mot de passe';

                            return 0;
                        }

                }

            // Processor $_POSTs
            protected function Process()
                {
                    // Process if $_POST is set
                    if(isset($_POST['userName'])) {
                            $this->useInfo['name']          =   (!empty($_POST['userName']))? ucfirst($_POST['userName']):"";
                            $this->useInfo['firstName']     =   (!empty($_POST['firstName']))? ucfirst($_POST['firstName']):"";
                            $this->useInfo['birthDate']     =   (!empty($_POST['year']) && !empty($_POST['month']) && !empty($_POST['day']))? $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day']:"";
                            $this->useInfo['languageM']     =   (!empty($_POST['langueM']))? $_POST['langueM']:"";
                            $this->useInfo['languageE']     =   (!empty($_POST['langueE']))? $_POST['langueE']:"";
                            $this->useInfo['niveau']        =   (!empty($_POST['level']))? $_POST['level']:"";
                            $this->useInfo['langueAjoutee'] =   (!empty($_POST['secondeLangue']))? $_POST['secondeLangue']:"";
                            $this->useInfo['niveau2']       =   (!empty($_POST['level2']))? $_POST['level2']:"";
                            $this->useInfo['email']         =   (!empty($_POST['mailInput']) && !empty($_POST['schools']))? $_POST['mailInput'].'@'.$_POST['schools']:"";
                            $this->useInfo['password1']     =   (!empty($_POST['password1']))? $_POST['password1']:"";
                            $this->useInfo['password2']     =   (!empty($_POST['password2']))? $_POST['password2']:"";

                            // Set password equivalent check
                            $pcheck =   ($this->useInfo['password1'] == $this->useInfo['password2'])? true:false;
                            if($pcheck == true) {
                                    // This is where you would run a validation on password
                                    // For instance -> check password length (I chose 8, but you never supplied that code)
                                    $length =   8;
                                    if(strlen($this->useInfo['password1']) >= 8) {
                                            $this->passCheck['password_sha']    =   sha1($this->useInfo['password1']);
                                            $this->useInfo['passe']             =   $this->passCheck['password_sha'];
                                            // Remove unused value
                                            unset($this->useInfo['password1'],$this->useInfo['password2']);
                                            // $this->passCheck['p2']     =   sha1($this->useInfo['password2']);
                                        }
                                    else
                                        $this->error['password']['length']  =   'Le mot de passe doit être de '.$length.'                                                                                     caractères';  
                                }
                            else
                                $this->error['password']['id']  =   'Les mots de passe ne sont pas identiques';
                    }

                    // Return only if the array is set and not empty
                    return (isset($this->useInfo) && !empty($this->useInfo))? $this->useInfo: 0;
                }

            public  function Validate()
                {
                    // Set all the prefs to array
                    $user   =   $this->Process();
                    // If the array is filled with something
                    if(!empty($user)) {
                            // Loop through the returned array
                            foreach($user as $key => $value) {
                                    // If there were any empty fields, assign them to an error array
                                    if(empty($value))
                                        $this->error['validate'][]  =   $key;
                                }

                            // This will only return the array IF there are no errors
                            // If you want something less strict, just remove the $this->error condition
                            return (!isset($this->error['validate']))? $user : 'err';
                        }
                    else
                        // Return false/0 if the user array is empty
                        return 0;
                }
        } ?>

连接类

<?php
    class   DBEngine
        {
            public  $con;
            public  $errors;
            public  function __construct($host="",$db = "",$user="",$pass="")
                {
                    try {
                            $this->con  =   new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
                        }
                    catch (Exception $e) {
                          $this->errors['connect']['message']    =   $e->getMessage();
                          $this->errors['connect']['error_code'] =   $e->getCode();
                          print_r($this->errors);
                        }
                }

            // Simple fetch and return method
            public  function Fetch($_sql)
                {
                    $query  =   $this->con->prepare($_sql);
                    $query->execute();
                    $this->errors['fetch'][]    =   $query->errorInfo();

                    if($query->rowCount() > 0) {
                            while($rows = $query->fetch(PDO::FETCH_ASSOC)) {
                                    $array[]    =   $rows;
                                }
                        }

                    return (isset($array) && $array !== 0 && !empty($array))? $array: 0;
                }

            // Simple write to db method
            public  function Write($_sql)
                {
                    $query  =   $this->con->prepare($_sql);
                    $query->execute();
                    $this->errors['insert'][]   =   $query->errorInfo();
                }
        } ?>

注册页面

<?php
//Registration workflow
ini_set('display_errors',1); 
error_reporting(E_ALL);
// Register User
if(isset($_POST['submit'])) {
        include('class.user.php');
        include('class.connect.php');
        $info   =   new SetUserInfo();
        // If info is all filled

        if(is_array($info->Validate())) {
                // If the passwords equal each other & is the correct
                // length of characters
                if(isset($info->passCheck['password_sha'])) {
                        // This is supposed to return the count
                        // if email exists already
                        $_emailInSys    =   $info->EmailCount();
                        // If email not in the system insert values for registration
                        if($_emailInSys == 0) {
                                // Insert into database
                                $success    =   $info->CreateRegistration();
                                // If success, forward to index
                                if($success == 1)
                                    header('Location: Index.php');
                            }
                    }
            }
    }
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Accueil</title>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/myjavascript.js"></script>
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<style>
label.error { color: red; float: left; clear: left; font-size: 10px; text-transform: uppercase; margin-bottom: 5px; }
#errors     { background-color: #C00; color: #FFF; border-radius: 4px; padding: 10px 20px; font-size: 14px; text-shadow: 1px 1px 4px rgba(0,0,0,0.4); display: none; font-family: Arial, Helvetica, sans-serif; }
#errorcont  { display: inline-block; }
</style>

</head>

<body>
<?php include("header.php"); ?>
<div id="formulaireInscription">
    <h3 id="titreIncrivez">Inscrivez-vous!</h3>
    <div id="numstyle">
    </div>
    <form action="Inscription.php" method="POST" id="registration">
        <div class="form-group">
            <div id="renseignementgenerale" class="form-group">
            <div id="errorcont">
                <div id="errors"></div>
            </div>
                <label for="userName">Nom:
                    <input type="text" class="form-control" name="userName" placeholder="Entrez votre nom" required="required">
                </label>
                <br />
                <label for="firstName">Prénom:</label>
                <input type="text" class="form-control" name="firstName" placeholder="Entrez votre prénom" required="required">
                <div class="form-group" id="birthdate">
                    <label>Date de naissance:</label>
                    <label for="dayInput">Jour</label>
                    <select name="day">
                        <option value="">Jour</option>
                        <?php for ($i = 1; $i <= 31; $i++) { ?>
                        <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                        <?php   } ?>
                    </select>
                    <label for"monthInput">Mois</label>
                    <select name="month">
                        <option value="">Mois</option>
                        <option value="01">Janvier</option>
                        <option value="02">Février</option>
                        <option value="03">Mars</option>
                        <option value="04">Avril</option>
                        <option value="05">Mai</option>
                        <option value="06">Juin</option>
                        <option value="07">juillet</option>
                        <option value="08">Aout</option>
                        <option value="09">Septembre</option>
                        <option value="10">Octobre</option>
                        <option value="11">Novembre</option>
                        <option value="12">Décembre</option>
                    </select>
                    <label for"yearInput">Année</label>
                    <select name="year">
                        <option value="">Année</option>
                        <?php
                                for ($i = 2014; $i >= 1930; $i--)
                                {
                                    echo '<option value="' . $i . '">' . $i . '</option>';
                                }
                            ?>
                    </select>
                </div>
                <div class="form-group" id="langueM">
                    <label>Langue maternelle:</label>
                    <select  name="langueM">
                        <option value="français">Français</option>
                        <option value="anglais">Anglais</option>
                        <option value="espagnol">Espagnol</option>
                    </select>
                </div>
                <div class="form-group" id="langueE">
                    <label>Langue étudiée:</label>
                    <select  name="langueE">
                        <option value="anglais">Anglais</option>
                        <option value="espagnol">Espagnol</option>
                        <option value="français">Français</option>
                    </select>
                    <label>Niveau:</label>
                    <select name=level id="niveau">
                        <option value="B1">B1</option>
                        <option value="B2">B2</option>
                        <option value="C1">C1</option>
                        <option value="C2">C2</option>
                    </select>
                    <img id="plus" title="Cliquer sur l'image pour ajouter une seconde langue" src="../res/images/boutons/plus.png"> <a class="level" ><strong><em>Comment choisir mon niveau?</em></strong> <span> B1:Je participe à des conversations sur des sujets<br />
                        simples et familiers.<br />
                        B2:Je peux discuter avec aisance et une certaine<br />
                        spontanéité.<br />
                        C1:Je m’exprime spontanément sans trop chercher<br />
                        mes mots<br />
                        C2:Je m’exprime et comprends sans efforts et<br />
                        je souhaite maintenir mon niveau. </span> </a><br />
                    <script>
                            document.getElementById('plus').onclick = function() {//cacher le bouton et afficher le select
                                    document.getElementById('addLanguage').style.display = 'inline';
                                    document.getElementById('plus').style.display = 'none';
                            }
                        </script>
                    <div id="addLanguage">
                        <select id="langu2" name="secondeLangue">
                            <option value="espagnol">Espagnol</option>
                            <option value="anglais">Anglais</option>
                            <option value="français">Français</option>
                        </select>
                        <label>Niveau:</label>
                        <select name=level2 id="niveau2">
                            <option value="B1">B1</option>
                            <option value="B2">B2</option>
                            <option value="C1">C1</option>
                            <option value="C2">C2</option>
                        </select>
                    </div>
                    </a>
                </div>
            </div>
            <label >Adresse email:</label>
            <div>
                <div class="mailliste">
                    <input name="mailInput" type="text" placeholder="Entrez votre email" required="required">
                    @
                    <select name="schools" onchange="VerifListe();">
                        <option value="rms.fr">rms.fr</option>
                        <option value="icade.es">icade.es</option>
                        <option value="esb.de">esb.de</option>
                    </select>
                    <a href=""><img id="question" src="../res/images/boutons/question.png"> <span> Vous pouvez vous inscrire<br />
                        uniquement avec <strong><em>votre adresse Email<br />
                        de votre école.</em></strong> Pour consulter la liste<br />
                        des écoles patenaires cliquez ici. </span> </a>
                </div>
                <br>
            </div>
        </div>
        <div class="form-group">
            <label for="inscriptionInputPassword1">Mot de passe:</label>
            <input type="password" class="form-control" id="password1" name="password1" placeholder="Entrez votre mode passe" required="required">
            <br>
            <input type="password" class="form-control" id="password2" name="password2" placeholder="Répétez votre mode passe" required="required">
        </div>
        <div class="myButtons">
            <input type="submit" name="submit" value="Inscription"/>
            <input type="button" value="Retour" onclick="document.location.href='Index.php';" />
        </div>
    </form>
</div>
<script>
$(document).ready(function() {
    <?php if(isset($info->error)) {
                foreach($info->error as $kind => $container) {
                        $imploder[] =   str_replace('"','\"',ucwords(implode("<br />",$container)));
                    }
                 ?>
                $("#errors").html("<?php echo implode("<br />",$imploder); ?>");
                $("#errors").delay(500).fadeIn("slow");
                $("#errors").delay(3000).fadeOut("slow");
    <?php } ?>

    // validate signup form on keyup and submit
    $("#registration").validate({
        rules: {
            userName: {
                required: true
            },
            day: {
                required: true
            },
            month: {
                required: true
            },
            year: {
                required: true
            },
            mail: {
                required: true,
                email: true//,
                //minlength: 4
            },
            password1: {
                required: true,
                minlength: 8
            },
            password2: {
                required: true,
                minlength: 8,
                equalTo: "#password1"
            }
        },
        messages: {
            mail: {
                required: "Nom d'utilisateur Obligatoire",
                email: "Adresse email invalide"
            },
            password1: {
                required: "Mot de passe requis",
                minlength: "8 caractères minimum"
            },
            password2: {
                required: "Mot de passe requis",
                minlength: "8 caractères minimum",
                equalTo: "Not the same"
            }
        }
    });
});
</script>
</body>
</html>

登录页面

<?php
session_start();
ini_set('display_errors',0); 
error_reporting(0);

    if(isset($_POST['cesam'])) {
            include('class.user.php');
            include('class.connect.php');
            $info       =   new SetUserInfo();
            $userData   =   $info->ValidateLogin($_POST['mail'],$_POST['pwd']);

            if($userData !== 0) {
                    $_SESSION['email']              =   $userData['mail'];
                    $_SESSION['nom']                =   $userData['nom'];
                    $_SESSION['date_de_naissance']  =   $userData['date_de_naissance'];
                    $_SESSION['langue_maternelle']  =   $userData['langue_maternelle'];
                    $_SESSION['langue_etudiee']     =   $userData['langue_etudiee'];
                    $_SESSION['niveau']             =   $userData['niveau'];
                    $_SESSION['langu2']             =   $userData['langu2'];
                    $_SESSION['niveau2']            =   $userData['niveau2'];
                    header("location: Accueil.php");
                }
        }
?><!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>Accueil</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<style>
label.error { color: red; float: left; clear: left; font-size: 10px; text-transform: uppercase; margin-bottom: 5px; }
#errors     { background-color: #C00; color: #FFF; border-radius: 4px; padding: 10px 20px; font-size: 14px; text-shadow: 1px 1px 4px rgba(0,0,0,0.4); display: none; font-family: Arial, Helvetica, sans-serif; }
#errorcont  { display: inline-block; }
</style>
</head>
<body>
<?php  include("header.php"); ?>
<div id="intro">
    <h2><span>Bladuo, Qu'est ce que c'est ?</span></h2>
</div>
<div id="errorcont">
    <div id="errors"></div>
</div>
<div id="formulaireConnexion">
    <form class="form-horizontal" action="Index.php" method="POST" id="login">
        <input type="email" name="mail" class="form-control" id="inputEmail3" placeholder="Email">
        <br />
        <input type="password" name="pwd" class="form-control" id="inputPassword3" placeholder="Mot de passe">
        <input type="checkbox">
        Se souvenir de moi
        <button type="submit" name="cesam" class="btn btn-lg btn-primary btn-block" role="button">Se connecter</button>
        <a href="Inscription.php" class="btn btn-lg btn-primary btn-block" role="button">S'inscrire</a>
    </form>
</div>
<div id="videoPresentation">
    <iframe width="560" height="315" src="//www.youtube.com/embed/CqSDWoAhvLU" allowfullscreen> </iframe>
</div>
<script>
$(document).ready(function() {
    <?php if(isset($info->error)) {
                foreach($info->error as $kind => $container) {
                        $imploder[] =   str_replace('"','\"',implode("",$container));
                    }
                 ?>
                $("#errors").html("<?php echo implode("",$imploder); ?>");
                $("#errors").delay(500).fadeIn("slow");
                $("#errors").delay(2000).fadeOut("slow");
    <?php } ?>

    // validate signup form on keyup and submit
    $("#login").validate({
        rules: {
            mail: {
                required: true,
                email: true//,
                //minlength: 4
            },
            pwd: {
                required: true,
                minlength: 8
            }
        },
        messages: {
            mail: {
                required: "Nom d'utilisateur Obligatoire",
                email: "Adresse email invalide"
            },
            pwd: {
                required: "Mot de passe requis",
                minlength: "8 caractères minimum"
            }
        }
    });
});
</script>
</body>
</html>

答案 1 :(得分:0)

reg.php中绑定两个参数:

   $getUsers->bindParam(1,$name);
   $getUsers->bindParam(2,$email);

然而,除非这个文件包含在其他地方,否则这些文件不会事先设定。

对于电子邮件,您会获得发布的字段,然后尝试使用变量$email而不是$mail

$mail = $_POST['mail'];

对于$name,您似乎永远不会在任何地方声明它。即:

$name = $_POST['name'];

我建议您启用错误报告,以便在发生时显示所有错误和警告,因为它会让您的生活更轻松,同时开发

答案 2 :(得分:0)

你绝对应该使用课程,这并不难,它可以帮助你整理代码。

我为你写了一个:

<?php
Class User{

private $name; 
private firstName;
private birthDate;
private languageM;
private languageE; 
private niveau;
private langueAjoutee;
private niveau2;
private email;
private password;

//la connection pdo
private $bdd;

    function __construct(){
        $this->bdd = new PDO('mysql:host=localhost;dbname=bladuo', 'root', '');
        $this->bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->bdd->exec('SET NAMES utf8');
    }

    function check_if_user_exists($email){
        $stmt= $this->bdd->prepare("SELECT email FROM `membres` WHERE email=?");
        $stmt->execute(array($email));
        return ($stmt->rowCount()==0);
    }

    function register_user(){
        try
        {
            $password_sha1 =sha1($this->password);
            $stmt =  $this->bdd->prepare('INSERT INTO members(nom,prenom,date_de_naissance,langue_maternelle,langue_etudiee,niveau,langu2,niveau2,email,passe)
                                   VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?,?)');
            $success = $stmt->execute(array($this->name , $this->firstName , 
                                            $this->birthDate, $this->languageM ,
                                            $this->languageE,$this->niveau,
                                            $this->langueAjoutee,$this->niveau2,
                                            $this->email,$password_sha1)); 
            if($success && $stmt->rowCount() > 0){  
                return true;
            }else{    
               echo "INSERT a echouer!!";
               return false;
            }
        }
        catch(Exception $e)
        {
            die('Erreur : '.$e->getMessage());
            return false;
        }   
    }

    function login_user($username, $password){
        $password_sha1 =sha1($this->password);

        $result = $this->bdd->prepare("SELECT * FROM members WHERE email=? AND passe=?");
        $result->bindParam(1,$mail);
        $result->bindParam(2,$password_sha);
        $result->execute();

        if($result->rowCount() == 1){ 
            $row = $result->fetch(PDO::FETCH_ASSOC);//print_r($row);
            return $row;
        }else{
            return false;
        }
    }

}
?>

注册用法:

<?php
include 'Users.php';

if(isset($_POST['userName'],
         $_POST['firstName'],
         $_POST['year'],
         $_POST['month'],
         $_POST['day'],
         $_POST['langueM'],
         $_POST['langueE'],
         $_POST['level'],
         $_POST['secondeLangue'],
         $_POST['level2'],
         $_POST['mailInput'],
         $_POST['schools'],
         $_POST['password1'], 
         $_POST['password2'])){

    //une instance du user object    
    $user = new User();

    $email =  $_POST['mailInput'].'@'.$_POST['schools'];
    if($_POST['password1'] === $_POST['password2']){
        if($user->check_if_user_exists($email)){
            //set les values
            $user->name = ucfirst($_POST['userName']); 
            $user->firstName = ucfirst($_POST['firstName']);
            $user->birthDate = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
            $user->languageM = $_POST['langueM']; 
            $user->languageE = $_POST['langueE']; 
            $user->niveau = $_POST['level'];
            $user->langueAjoutee = $_POST['secondeLangue'];
            $user->niveau2 = $_POST['level2'];
            $user->email =  $_POST['mailInput'].'@'.$_POST['schools'];
            $user->password = $_POST['password1'];
            //register the user
            if($user->register_user()){
                // "User registered!"   
                header('Location: Index.php');
            }else{
                die("user failed to register");
            }

        }else{
            die("User exist already!");
        }       
    }else{
        die("Password n'est pas correct");
    }

}

登录用法:

<?php
include 'Users.php';

if(isset($_POST['mail'],$_POST['pwd'])){    
    $mail = $_POST['mail'];
    $password = $_POST['pwd'];  

    $user = new User();
    if($user->login_user($mail, $pass)){
        header("location: Accueil.php");
        exit;       
    }else{
        die("mot de passe ou mail invalid!");
    }
}

未经测试,但您应该明白这一点,我相信如果发现任何拼写错误,您可以解决它。

希望这会有所帮助