Depuis plusieurs jours je bloque sur l'inscription du membre, cela me dit que la requete SQL à un probleme.
Je suis en structure MVC.
Je recupére bien toute mes valeurs.
Voici mon controleur :
Code : Tout sélectionner
<?php
// unset($_SESSION);
//Démarrer une nouvelle session
session_start();
require_once(dirname(__FILE__).'/../Public/Utiles/regex.php');
//Appel de la fonction melange token
require_once(dirname(__FILE__).'/../Public/Utiles/Fonctions/token.php');
// Inclure le modele
require_once(dirname(__FILE__).'/../Modeles/ChoixAvatars.php');
require_once(dirname(__FILE__).'/../Modeles/Utilisateur.php');
//Fichier pour envoi de mail en local et en prod
require_once(dirname(__FILE__).'/../Public/Utiles/phpmailer.php');
$code = trim(filter_input(INPUT_GET, 'code', FILTER_SANITIZE_NUMBER_INT));
$IdAvatar = 0;
// Appel de la méthode voirTable pour récupérer les données de la table
$choixAvatar = new ChoixAvatars();
$results = $choixAvatar->voirAvatars();
//Methode pour recupérer l'id
$idMax = new Utilisateurs();
$returnMaxId = $idMax->maxId();
//On verifie que le formulaire est envoyé
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$avatars = trim(filter_input(INPUT_POST, 'avatars', FILTER_SANITIZE_NUMBER_INT));
$validation = intval(trim(filter_input(INPUT_POST, 'validation', FILTER_SANITIZE_NUMBER_INT)));
switch ($validation) {
case 1: //Connexion
//Champ mail
$mailConnexion = trim(filter_input(INPUT_POST, 'mailConnexion', FILTER_SANITIZE_EMAIL));
if(!empty($mailConnexion)){
// Mettre l'adresse e-mail en minuscules
$mailConnexion = strtolower($mailConnexion);
// Supprimer les espaces vides de l'adresse e-mail
$mailConnexion = str_replace(' ', '', $mailConnexion);
if(strlen($mailConnexion)>100){
$error["mailConnexion"] = 'La longueur du mail doit être inférieure à 100 caractères.';
}
if (preg_match(REGEX_MAIL_PREG_MATCH_INJECTION_SQL, $mailConnexion)) {
// La variable est valide, vous pouvez exécuter le code approprié ici
} else {
// La variable n'est pas valide, vous pouvez afficher un message d'erreur ou effectuer une action appropriée
$error["mailConnexion"] = 'Le mail n\'est pas au bon format ou contient une injection SQL.';
}
} else {
$error["mailConnexion"] = 'Vous devez entrer une adresse mail.';
}
//Mot de passe connexion
$mdpConnexion = trim(filter_input(INPUT_POST, 'mdpConnexion', FILTER_SANITIZE_STRING));
if(!empty($mdpConnexion)){
if (strlen($mdpConnexion) < 6) {
$error["mdpConnexion"] = 'Le mot de passe doit contenir au moins 6 caractères.';
} elseif (strlen($mdpConnexion) > 20) {
$error["mdpConnexion"] = 'Le mot de passe doit contenir moins de 21 caractères.';
}
if (preg_match('/' . preg_quote(REGEX_MDP, '/') . '/', $mdpConnexion)) {
// La variable est valide, vous pouvez exécuter le code approprié ici
} else {
// La variable n'est pas valide, vous pouvez afficher un message d'erreur ou effectuer une action appropriée
$error["mdpConnexion"] = 'Le mot de passe n\'est pas au bon format ou contient une injection SQL.';
}
} else {
$error["mdpConnexion"] = 'Le mot de passe est obligatoire.';
}
// var_dump($mailConnexion);
// var_dump($mdpConnexion);
// exit;
// Revoir une fois inscription pour valider la redirection et voir aussi mot de passe oublier
// if(!empty($_POST['mailConnexion']) && !empty($_POST['mdpConnexion'])) {
// //Extraction des posts dans les varibles
// extract($_POST);
// //Récupération des infos de l'utilisateur
// $utilisateur = new Utilisateurs();
// $infoUtilisateur = $utilisateur->findOne($mailConnexion);
// //Vérification de la correspondance des mots de passe
// if(!is_object($infoUtilisateur) && $infoUtilisateur == false){
// $code = 12; //Pseudo ou mot de passe erroné.
// } else {
// if($infoUtilisateur->actif ==1){
// if(password_verify($mdpConnexion, $infoUtilisateur->mdpc)){
// $_SESSION['auth'] = $infoUtilisateur;
// header('Location: /controllers/connecter-ctrl.php');
// } else {
// $code = 12; //Pseudo ou mot de passe erroné.
// }
// } else {
// $code = 13; //Compte désactivé ou pas activé.
// }
// }
// }
break;
case 2: //Inscription
//Champ mail
$mailInscription = trim(filter_input(INPUT_POST, 'mailInscription', FILTER_SANITIZE_EMAIL));
if(!empty($mailInscription)){
$testRegex = filter_var($mailInscription, FILTER_VALIDATE_EMAIL);
// Mettre l'adresse e-mail en minuscules
$mailInscription = strtolower($mailInscription);
if(!$testRegex){
$error["mailInscription"] = 'Le mail n\'est pas au bon format.';
} if(strlen($mailInscription)>100){
$error["mailInscription"] = 'La longueur du mail doit inférieur à 100 caractéres.';
}
} else {
$error["mailInscription"] = 'Vous devez entrer une adresse mail.';
}
$mailconfirmationInscription = trim(filter_input(INPUT_POST, 'mailconfirmationInscription', FILTER_SANITIZE_EMAIL));
if(!empty($mailconfirmationInscription)){
$testRegex = filter_var($mailconfirmationInscription, FILTER_VALIDATE_EMAIL);
// Mettre l'adresse e-mail en minuscules
$mailconfirmationInscription = strtolower($mailconfirmationInscription);
if(!$testRegex){
$error["mailconfirmationInscription"] = 'Le mail n\'est pas au bon format.';
} if(strlen($mailInscription)>100){
$error["mailconfirmationInscription"] = 'La longueur du mail doit inférieur à 100 caractéres.';
}
} else {
$error["mailconfirmationInscription"] = 'Vous devez entrer une adresse mail.';
}
//Verification des mails
if($mailInscription && $mailconfirmationInscription) {
if ($mailInscription != $mailconfirmationInscription) {
$error["mailInscription"] = 'Les mails saisis sont différents.';
$error["mailconfirmationInscription"] = 'Les mails saisis sont différents.';
}
}
//Pseudo
$pseudo = trim(filter_input(INPUT_POST, 'pseudo', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
// $testRegex = preg_match('/'.REGEX_NUMBER_AND_LETTER.'/', $pseudo);
// if(!$testRegex){
// $error["pseudo"] = 'Le pseudo n\'est pas au bon format.';
// }
if(!empty($pseudo)){
if(strlen($pseudo)<2 || strlen($pseudo)>20){
$error["pseudo"] = 'Le pseudo doit etre compris entre 2 et 20 caractéres.';
}
} else {
$error["pseudo"] = 'Le pseudo est obligatoire.';
}
//Mot de passe inscription mdpInscription
$mdpInscription = trim(filter_input(INPUT_POST, 'mdpInscription', FILTER_SANITIZE_STRING));
if(!empty($mdpInscription)){
if(strlen($mdpInscription)<6 || strlen($mdpInscription)>20){
$error["mdpInscription"] = 'Le mot de passe n\'est pas compris entre 6 et 20 caractéres.';
}
} else {
$error["mdpInscription"] = 'Le mot de passe est obligatoire.';
}
//Mot de passe inscription mdpConfirmationInscription
$mdpConfirmationInscription = trim(filter_input(INPUT_POST, 'mdpConfirmationInscription', FILTER_SANITIZE_STRING));
if(!empty($mdpConfirmationInscription)){
if(strlen($mdpConfirmationInscription)<6 || strlen($mdpConfirmationInscription)>20){
$error["mdpConfirmationInscription"] = 'Le mot de passe n\'est pas compris entre 6 et 20 caractéres.';
}
} else {
$error["mdpConfirmationInscription"] = 'Le mot de passe est obligatoire.';
}
//Verification des mots de passe
if($mdpInscription && $mdpConfirmationInscription) {
if($mdpInscription != $mdpConfirmationInscription) {
$error["mdpInscription"] = 'Les mots de passe sont différents.';
$error["mdpConfirmationInscription"] = 'Les mots de passe sont différents.';
}
}
//Avatars
if (isset($_POST['avatar'])) {
// Récupérer la valeur de la clé "avatar"
$IdAvatar = $_POST['avatar'];
} else {
// Gérer le cas où la clé "avatar" n'est pas présente dans le tableau $_POST
$IdAvatar == 0; // Ou toute autre valeur par défaut que vous souhaitez attribuer
}
if(!empty($IdAvatar)){
if(strlen($IdAvatar)>2){
$error["avatar"] = 'Les pirates sont interdits.';
}
}
//Traitement calcul
$somme = $_SESSION["nbr1"] + $_SESSION["nbr2"];
$sommeReponse = trim(filter_input(INPUT_POST, 'sommeReponse', FILTER_SANITIZE_NUMBER_INT));
if(empty($sommeReponse)){
$error["sommeReponse"] = 'Réponse manquante.';
}
if(!empty($sommeReponse)){
if(strlen($sommeReponse)>2){
$error["sommeReponse"] = 'Trop de chiffres rentrés.';
}
}
if($_SESSION["nbr1"] > 50 || $_SESSION["nbr1"] < 0){
$error["sommeReponse"] = 'Les pirates sont interdits.';
}
if($_SESSION["nbr2"] > 10 || $_SESSION["nbr2"] < 1){
$error["sommeReponse"] = 'Les pirates sont interdits.';
}
if(!empty($somme != $sommeReponse)){
$error["sommeReponse"] = 'Mauvaise réponse.';
}
// unset($_SESSION['nbr1']);
// unset($_SESSION['nbr2']);
//Affectation des valeurs
$mdp = $mdpConfirmationInscription;
$mail = $mailconfirmationInscription;
//Crytptage du mot de passe mdpc
$mdpc=password_hash($mdp, PASSWORD_DEFAULT);
//////// var
// $nbr1 = $_SESSION["nbr1"];
// $nbr2 = $_SESSION["nbr2"];
// var_dump($mailInscription);
// var_dump($mailconfirmationInscription);
//var_dump($mail);
// var_dump($pseudo);
// var_dump($mdpInscription);
// var_dump($mdpConfirmationInscription);
//var_dump($avatarId);
// var_dump($nbr1);
// var_dump($nbr2);
// var_dump($somme);
// var_dump($sommeReponse);
// var_dump($mdpc);
// var_dump($IdAvatar);
//exit;
//On verifie que le tableau erreur est vide pour enr en base de donnees
if(empty($error)){
$cptActiver = 0; //compte activer par defaut 0
$IdRole = 2; //role par defaut 2
$effacer = 0; //Mettre à 1 si demande de suppression
// var_dump($returnMaxId);
// exit;
//Melange de caractere et chiffre via la fonction
$token = $returnMaxId.str_random(60);
//////// var
// $nbr1 = $_SESSION["nbr1"];
// $nbr2 = $_SESSION["nbr2"];
// var_dump($mailInscription);
// var_dump($mailconfirmationInscription);
// var_dump($mail);
// var_dump($pseudo);
// var_dump($mdpInscription);
// var_dump($mdpConfirmationInscription);
// var_dump($IdAvatar);
// var_dump($nbr1);
// var_dump($nbr2);
// var_dump($somme);
// var_dump($sommeReponse);
// var_dump($mdpc);
// var_dump($cptActiver);
// var_dump($IdRole);
// var_dump($effacer);
// var_dump($token);
// exit;
//On recupere les valeurs hydrate
$utilisateur = new Utilisateurs('', $mail, $pseudo, $mdpc, $cptActiver, $IdRole, $IdAvatar, $token, $effacer);
//$idUtilisateur = $returnMaxId;
//On creer l'utilisateur en base
$exception = $utilisateur->create();
if ($exception == 1){
$nettoyageBase = $utilisateur->checkUserValidate();
//On recupére le dernier id creer de l'instance précédente
// Variable pour l'envoi du mail
$inscription = 'inscription';
$code = 8;
$sujet="Validation d'inscription au site Yaka";
$message = "Bonjour, <br> Merci de votre inscription. <br> Afin de valider votre inscription, veuillez cliquer sur le lien ci-dessous : <br> <a href=\"https://intranet.easykode.com/controllers/neutreInscription-ctrl.php?token=".$token."&code=".$code."&inscription=".$inscription."\"><button type=\"button\">Validation</button></a>";
$message2 = 'Bonjour,\nMerci de votre inscription.\nAfin de valider votre inscription veuillez, copier le lien suivant dans votre navigateur : https://intranet.easykode.com/controllers/neutreInscription-ctrl.php?token='.$token.'&code='.$code.'&inscription='.$inscription;
$expediteur = $mail;
// appel de la fonction pour envoyer mail
sendmail($sujet,$message,$message2,$expediteur);
$code = 1; //Terminer votre inscription en validant le mail envoyer.
header('Location: /controllers/neutreInscription-ctrl.php?code='.$code);
exit;
} elseif ($exception === 2) {
$code = 2; //Une erreur SQL est survenue
header('Location: /Controlleurs/connexionInscription-ctrl.php?code='.$code);
exit;
} elseif ($exception === 3) {
$code = 3; //Le mail existe déja
header('Location: /Controlleurs/connexionInscription-ctrl.php?code='.$code);
exit;
} elseif ($exception === 6) {
$code = 6; //Le mail et le pseudo existe deja
header('Location: /Controlleurs/connexionInscription-ctrl.php?code='.$code);
exit;
} elseif ($exception === 5) {
$code = 5; //Le pseudo existe déja
header('Location: /Controlleurs/connexionInscription-ctrl.php?code='.$code);
exit;
}
}
}
}
include(dirname(__FILE__).'/../Vues/connexionInscription.php');Code : Tout sélectionner
<?php
require_once(dirname(__FILE__).'/../Public/Utiles/database.php');
class Utilisateurs
{
private $id;
private $mail;
private $pseudo;
private $mdpc;
private $cptActiver;
private $IdRole;
private $IdAvatar;
private $token;
private $effacer;
private $pdo;
//Methode magique pour hydraté l'objet
public function __construct($id = NULL, $mail = NULL, $pseudo = NULL, $mdpc = NULL, $cptActiver = NULL, $IdRole = NULL, $IdAvatar = NULL, $token = NULL, $effacer = NULL)
{
$this->id = $id;
$this->mail = $mail;
$this->pseudo = $pseudo;
$this->mdpc = $mdpc;
$this->cptActiver = $cptActiver;
$this->IdRole = $IdRole;
$this->IdAvatar = $IdAvatar;
$this->token = $token;
$this->effacer = $effacer;
$this->pdo = Database::getInstance();
}
function __set($property, $value)
{
$this->$property = $value;
}
//verifie que le mail existe
public static function checkDuplicate($mail)
{
$checkMailSql ="SELECT `mail`
FROM `utilisateurs`
WHERE `mail`= :mail ";
$pdo = Database::getInstance();
$stmtCheckMailReq = $pdo->prepare($checkMailSql);
$stmtCheckMailReq->bindValue(':mail',$mail,PDO::PARAM_STR);
try {
$stmtCheckMailReq->execute();
return $stmtCheckMailReq->fetchColumn();
} catch (PDOException $ex) {
return false;
}
}
//verifie que le pseudo existe
public static function pseudoDuplicate($pseudo)
{
$checkPseudoSql ='SELECT `pseudo`
FROM `utilisateurs`
WHERE `pseudo`= :pseudo;';
$pdo = Database::getInstance();
$stmtCheckPseudoReq = $pdo->prepare($checkPseudoSql);
$stmtCheckPseudoReq->bindValue(':pseudo',$pseudo,PDO::PARAM_STR);
try {
$stmtCheckPseudoReq->execute();
return $stmtCheckPseudoReq->fetchColumn();
} catch (PDOException $ex) {
return false;
}
}
public function maxID()
{
/*requete maxid*/
$sql = 'SELECT max(id) AS id FROM `utilisateurs`;';
$recupidmax = $this->pdo->prepare($sql);
$varqidmax=array();
/* recherche max id */
$recupidmax->execute($varqidmax);
while($resultmaxid=$recupidmax->fetch())
{
return $maxid=$resultmaxid->id+1;
}
}
//Creation de l'utilisateur avec vérification que le mail et pseudo n'existe pas
public function create()
{
if($this->checkDuplicate($this->mail) == false && $this->pseudoDuplicate($this->pseudo) == false){
$sql = 'INSERT INTO utilisateurs ($mail, $pseudo, $mdpc, $cptActiver, $IdRole, $IdAvatar, $token, $effacer) VALUES (:mail, :pseudo, :mdpc, :cptActiver, :IdRole, :IdAvatar, :token, :effacer);';
$req = $this->pdo->prepare($sql);
$req->bindValue(':mail', $this->mail,PDO::PARAM_STR);
$req->bindValue(':pseudo', $this->pseudo,PDO::PARAM_STR);
$req->bindValue(':mdpc', $this->mdpc,PDO::PARAM_STR);
$req->bindValue(':cptActiver', $this->cptActiver,PDO::PARAM_INT);
$req->bindValue(':IdRole', $this->IdRole,PDO::PARAM_INT);
$req->bindValue(':IdAvatar', $this->IdAvatar,PDO::PARAM_INT);
$req->bindValue(':token', $this->token,PDO::PARAM_STR);
$req->bindValue(':effacer', $this->effacer,PDO::PARAM_INT);
try {
$req->execute(); //L'utilisateur a bien été ajouté
return 1; //Terminer votre inscription en validant le mail envoyer.
} catch (PDOException $ex) {
return 2; //Erreur contacter l\'administrateur.
}
}elseif($this->checkDuplicate($this->mail) != false && $this->pseudoDuplicate($this->pseudo) != false){
return 6; //Le mail et le pseudo existe déjà
}elseif($this->checkDuplicate($this->mail) != false){
return 3; //Le mail existe déja
}elseif($this->pseudoDuplicate($this->pseudo) != false){
return 5; //Le pseudo existe déja
}
}
//Effacer utilisateur qui ne valide pas son inscription
public function checkUserValidate()
{
$sql = 'DELETE FROM `utilisateurs` WHERE `cptActiver` = 0 AND `maj` = `creation` AND (TIMEDIFF(NOW(), `maj`)) > "03:00:00";';
$req = $this->pdo->prepare($sql);
try {
$req->execute(); //Effacement utilisateur
$req->rowCount();
return 18; //Bonne exécution
} catch (PDOException $ex) {
return 2; //Erreur contacter l\'administrateur.
}
}
public function validerMail($mail){
try{
$sql = 'UPDATE `utilisateurs`
SET `maj` = NOW(),
`cptActiver` = 1
WHERE `mail` = :mail;';
$sth = $this->pdo->prepare($sql);
$sth->bindValue(':mail',$mail,PDO::PARAM_STR);
if($sth->execute()){
$sth->rowCount();
return 7; //Merci, votre compte est activer.
}
}
catch(PDOException $ex){
return 4; //Les pirates sont interdit ici.
}
}
public function findOne($mail)
{
$sql = 'SELECT `id`, `mail`, `pseudo`, `mdpc`, `cptActiver`, `IdRole`, `IdAvatar`, `token`, `effacer` FROM `utilisateurs` WHERE `mail`= :mail;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':mail',$mail,PDO::PARAM_STR);
try {
if($req->execute()) {
return $req->fetch(PDO::FETCH_OBJ);
}
} catch (PDOException $ex) {
return false;
}
}
public function findOneInscrit($id)
{
$sql = 'SELECT `id`, `mail`, `pseudo`, `mdpc`, `cptActiver`, `IdRole`, `IdAvatar`, `token`, `effacer` FROM `utilisateurs` WHERE `id`= :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id',$id,PDO::PARAM_STR);
try {
if($req->execute()) {
return $req->fetch(PDO::FETCH_OBJ);
}
} catch (PDOException $ex) {
return false;
}
}
public function findAll()
{
$sql = 'SELECT `id`, `mail`, `pseudo`, `mdpc`, `cptActiver`, `IdRole`, `IdAvatar`, `token`, `effacer` FROM `utilisateurs`';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->execute();
return($req->fetchAll()); // deja en fetch obj declarer dans database (PDO::FETCH_OBJ);
}
// public function findAll($limit, $records_per_page)
// {
// $offset = ($limit - 1) * $records_per_page;
// $sql = "SELECT `id`, `mail`, `pseudo`, `mdpc`,`status`, `role`, `creation`, `actif` FROM `utilisateurs` LIMIT :limit OFFSET :offset";
// $pdo = Database::getInstance();
// $req = $pdo->prepare($sql);
// $req->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
// $req->bindValue(':offset', $offset, PDO::PARAM_INT);
// $req->execute();
// return $req->fetchAll(PDO::FETCH_OBJ);
// }
public function ReinitMdp($token)
{
$sql = 'SELECT `id`, `mail`, `pseudo`, `mdpc`, `cptActiver`, `IdRole`, `IdAvatar`, `token`, `effacer` FROM `utilisateurs` WHERE `token`= :token;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':token',$token,PDO::PARAM_STR);
try {
if($req->execute()) {
return $req->fetch(PDO::FETCH_OBJ);
}
} catch (PDOException $ex) {
return false;
}
}
public function validerNewMdpc($token,$mdpc){
try{
$sql = 'UPDATE `utilisateurs`
SET `maj` = NOW(),
`mdpc` = :mdpc
WHERE `token` = :token;';
$sth = $this->pdo->prepare($sql);
$sth->bindValue(':token',$token,PDO::PARAM_STR);
$sth->bindValue(':mdpc',$mdpc,PDO::PARAM_STR);
if($sth->execute()){
$sth->rowCount();
return 17; //Mot de passe modifier avec succès.
}
}
catch(PDOException $ex){
return 4; //Les pirates sont interdit ici.
}
}
public function compter()
{
$sql = 'SELECT COUNT(*) AS total FROM utilisateurs;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
try {
if($req->execute()) {
return $req->fetch(PDO::FETCH_OBJ);
}
} catch (PDOException $ex) {
return false;
}
}
////////////////////////// EN COURS FICHE INSCRIT ////////////////////////////////////
//verifie que le mail existe
public static function checkDuplicateUpdate($mail, $id)
{
$checkMailSql ='SELECT `mail`
FROM `utilisateurs`
WHERE `mail`= :mail AND `id` != :id;';
$pdo = Database::getInstance();
$stmtCheckMailReq = $pdo->prepare($checkMailSql);
$stmtCheckMailReq->bindValue(':mail',$mail,PDO::PARAM_STR);
$stmtCheckMailReq->bindValue(':id',$id,PDO::PARAM_INT);
try {
$stmtCheckMailReq->execute();
return $stmtCheckMailReq->fetchColumn();
} catch (PDOException $exception) {
return false; /// retourne 4 Mail existant ///
}
}
//verifie que le pseudo existe
public static function pseudoDuplicateUpdate($pseudo, $id)
{
$checkPseudoSql ='SELECT `pseudo`
FROM `utilisateurs`
WHERE `pseudo`= :pseudo AND `id` != :id;';
$pdo = Database::getInstance();
$stmtCheckPseudoReq = $pdo->prepare($checkPseudoSql);
$stmtCheckPseudoReq->bindValue(':pseudo',$pseudo,PDO::PARAM_STR);
$stmtCheckPseudoReq->bindValue(':id',$id,PDO::PARAM_INT);
try {
$stmtCheckPseudoReq->execute();
return $stmtCheckPseudoReq->fetchColumn();
} catch (PDOException $exception) {
return false;/// retourne 5 pseudo existe deja ///
}
}
//// fonction update mise a jour avec controle ///////
public function update($id)
{
// if($this->checkDuplicateUpdate($this->mail) == false && $this->pseudoDuplicateUpdate($this->pseudo) == false){
$sql ='UPDATE `utilisateurs` SET `mail` = :mail, `pseudo` = :pseudo, `status` = :status, `role` = :role WHERE `ID` = :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id', $this->id, PDO::PARAM_INT);
$req->bindValue(':mail', $this->mail, PDO::PARAM_STR);
$req->bindValue(':pseudo', $this->pseudo, PDO::PARAM_STR);
$req->bindValue(':status', $this->status, PDO::PARAM_INT);
$req->bindValue(':role', $this->role, PDO::PARAM_INT);
try {
$req->execute();
if($req->rowCount() != 0) {
return 25; //Message mis à jour
}
} catch (PDOException $ex) {
return 24; //Message pas mis à jour
}
// }elseif($this->checkDuplicate($this->mail) != false && $this->pseudoDuplicate($this->pseudo) != false){
// return 6; //Le mail et le pseudo existe déjà
// }elseif($this->checkDuplicate($this->mail) != false){
// return 3; //Le mail existe déja
// }elseif($this->pseudoDuplicate($this->pseudo) != false){
// return 5; //Le pseudo existe déja
// }
}
public function updateFicheUtilisateur($id)
{
// if($this->checkDuplicateUpdate($this->mail) == false && $this->pseudoDuplicateUpdate($this->pseudo) == false){
$sql ='UPDATE `utilisateurs` SET `mail` = :mail, `pseudo` = :pseudo WHERE `ID` = :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id', $this->id, PDO::PARAM_INT);
$req->bindValue(':mail', $this->mail, PDO::PARAM_STR);
$req->bindValue(':pseudo', $this->pseudo, PDO::PARAM_STR);
try {
$req->execute();
if($req->rowCount() != 0) {
return 25; //Message mis à jour
}
} catch (PDOException $ex) {
return 24; //Message pas mis à jour
}
}
/// mise a jour mot de passe ///
public function mdpadmin($id)
{
$sql ='UPDATE `utilisateurs` SET `mdpc` = :mdpc WHERE `ID` = :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id', $this->id, PDO::PARAM_INT);
$req->bindValue(':mdpc', $this->mdpc, PDO::PARAM_STR);
try {
$req->execute();
if($req->rowCount() != 0) {
return 32; //Mot de passe mis a jour
}
} catch (PDOException $ex) {
return 33; //Mot de passe pas mis a jour
}
}
public function desactiver($id)
{
$sql = 'UPDATE utilisateurs SET `status` = :status WHERE `id` = :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id', $this->id, PDO::PARAM_INT);
$req->bindValue(':status', $this->status, PDO::PARAM_INT);
try {
$req->execute();
if($req->rowCount() != 0) {
return 26; //Profil desactiver
}
} catch (PDOException $ex) {
return 27; //Profil pas desactiver
}
}
public function reactiver($id)
{
$sql = 'UPDATE utilisateurs SET `status` = :status WHERE `id` = :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id', $this->id, PDO::PARAM_INT);
$req->bindValue(':status', $this->status, PDO::PARAM_INT);
try {
$req->execute();
if($req->rowCount() != 0) {
return 28; //Profil reactiver
}
} catch (PDOException $ex) {
return 29; //Profil pas reactiver
}
}
public function supprimer($id)
{
$sql = 'DELETE FROM utilisateurs WHERE `id`= :id;';
$pdo = Database::getInstance();
$req = $pdo->prepare($sql);
$req->bindValue(':id', $this->id, PDO::PARAM_INT);
try {
$req->execute();
if($req->rowCount() != 0) {
return 30; //L'utilisateur supprimer
}
} catch (PDOException $ex) {
return 31; //L'utilisateur ,'a pas été supprimer
}
}
///// Fonction recherche ++++ //////////////////
public function recherchePlus($filtre, $recherche) {
// Valider la valeur de $filtre pour éviter les attaques d'injection SQL
$valid_filtre = in_array($filtre, ['id', 'pseudo', 'mail', 'status', 'role', 'actif']) ? $filtre : 'pseudo';
// Si le filtre est status, role ou actif et que la recherche est égale à zéro, ajuster la requête SQL
if (in_array($valid_filtre, ['status', 'role', 'actif']) && $recherche === '0') {
$stmt = $this->pdo->prepare("SELECT * FROM utilisateurs WHERE $valid_filtre = 0");
} else {
// Requête SQL préparée pour récupérer les utilisateurs correspondants
$stmt = $this->pdo->prepare("SELECT * FROM utilisateurs WHERE $valid_filtre LIKE :recherche");
$stmt->bindValue(':recherche', '%'.$recherche.'%');
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Vérifier si la requête a renvoyé des résultats
if (empty($result)) {
return ['result' => [], 'code' => 37]; // Aucun utilisateur trouvé
}
// Affichage des résultats
foreach ($result as $row) {
// Afficher les informations de l'utilisateur
}
return ['result' => $result, 'code' => 0];
}
/// Pagination ///
public function findWithPagination($offset, $limit) {
$sql = "SELECT * FROM utilisateurs LIMIT :offset, :limit";
$pdo = Database::getInstance();
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
public function recherchePlusPaginee($filtre, $recherche, $offset, $limit) {
// Valider la valeur de $filtre pour éviter les attaques d'injection SQL
$valid_filtre = in_array($filtre, ['id', 'pseudo', 'mail', 'status', 'role', 'actif']) ? $filtre : 'pseudo';
// Si le filtre est status, role ou actif et que la recherche est égale à zéro, ajuster la requête SQL
if (in_array($valid_filtre, ['status', 'role', 'actif']) && $recherche === '0') {
$sql = "SELECT * FROM utilisateurs WHERE $valid_filtre = 0";
} else {
$sql = "SELECT * FROM utilisateurs WHERE $valid_filtre LIKE :recherche";
$recherche = '%'.$recherche.'%';
}
$sql .= " LIMIT :offset, :limit";
$pdo = Database::getInstance();
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
// Si la recherche n'est pas égale à zéro, lier la valeur de :recherche à la requête SQL
if (isset($recherche)) {
$stmt->bindValue(':recherche', $recherche);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Vérifier si la requête a renvoyé des résultats
if (empty($result)) {
return ['result' => [], 'code' => 37]; // Aucun utilisateur trouvé
}
// Affichage des résultats
foreach ($result as $row) {
// Afficher les informations de l'utilisateur
}
}
// public static function findAll($search='', $limit=null, $offset=0, $deactivated=0){
// try{
// if(!is_null($limit)){ // Si une limite est fixée, il faut tout lister
// if($deactivated){ //true ou 1 veut on inclure les desac oui ou non
// $sql = 'SELECT * FROM `registration_employs`
// WHERE `lastname` LIKE :search
// OR `firstname` LIKE :search
// ORDER BY `lastname`
// LIMIT :limit OFFSET :offset;';
// } else {
// $sql = 'SELECT * FROM `registration_employs`
// WHERE `lastname` LIKE :search AND `status` = 1
// OR `firstname` LIKE :search AND `status` = 1
// ORDER BY `lastname`
// LIMIT :limit OFFSET :offset;';
// }
// } else {
// if($deactivated){
// $sql = 'SELECT * FROM `registration_employs`
// WHERE `lastname` LIKE :search
// OR `firstname` LIKE :search
// ORDER BY `lastname`;';
// } else {
// $sql = 'SELECT * FROM `registration_employs`
// WHERE `lastname` LIKE :search AND `status` = 1
// OR `firstname` LIKE :search AND `status` = 1
// ORDER BY `lastname`;';
// }
// }
// $pdo = Database::getInstance();
// $stmt = $pdo->prepare($sql);
// $stmt->bindValue(':search','%'.$search.'%',PDO::PARAM_STR);
// if(!is_null($limit)){
// $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
// $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
// }
// $stmt->execute();
// return($stmt->fetchAll()); // deja en fetch obj declarer dans database (PDO::FETCH_OBJ);
// }
// catch(PDOException $ex){
// return false;
// }
// }
// public function modifyPassword()
// {
// $sql = 'UPDATE `registration_employs`
// SET `mdpc`=:password
// WHERE `id` = :id;';
// $req = $this->pdo->prepare($sql);
// $req->bindValue(':password', $this->mdpc,PDO::PARAM_STR);
// $req->bindValue(':id', $this->id,PDO::PARAM_STR);
// try {
// $test =$req->execute();
// return 13;
// } catch (PDOException $ex) {
// return 4;
// }
// }
// // Methode pour compter les salariés
// public static function count($search){
// $pdo = Database::getInstance();
// try{
// $sql = 'SELECT * FROM `registration_employs`
// WHERE `lastname` LIKE :search
// OR `firstname` LIKE :search;';
// $stmt = $pdo->prepare($sql);
// $stmt->bindValue(':search','%'.$search.'%',PDO::PARAM_STR);
// $stmt->execute();
// return($stmt->rowCount());
// }
// catch(PDOException $ex){
// return 4;
// }
// }
// // Effacement des données
// public static function delete($id)
// {
// $pdo = Database::getInstance();
// $sql = "DELETE FROM `registration_employs` WHERE `id` = :id;";
// $sth = $pdo->prepare($sql);
// $sth->bindValue(':id',$id,PDO::PARAM_INT);
// try {
// $sth->execute();
// if($sth->rowCount()!=0)
// return 15; // La fiche à bien été supprimée.
// // pas besoin de faire un else car le return stop le code.
// return 16; // La fiche n'a pas été suppriméé.
// }
// catch(PDOException $ex){
// return 4; // Erreur SQL.
// }
// }
// // Mise a 0/1 du status
// public static function updateStatus($id,$status){
// $pdo = Database::getInstance();
// $sql = 'UPDATE `registration_employs`
// SET `status` = :status
// WHERE `id` = :id;';
// $sth = $pdo->prepare($sql);
// $sth->bindValue(':status',$status,PDO::PARAM_INT);
// $sth->bindValue(':id',$id,PDO::PARAM_INT);
// try{
// $sth->execute();
// if($sth->rowCount()!=0){
// if($status == 1){
// return 19; // L'utilisateur à été réactivé.
// } else {
// return 17; // L'utilisateur à été désactivé.
// }
// }
// return 18; // La fiche n'a pas été désactivé.
// }
// catch(PDOException $ex){
// return 4; // Erreur SQL.
// }
// }
// //Methode pour mettre a jour l'utilisateur
// public function update()
// {
// $oldEmail = $this->findOne()->mail;
// if(!($this->checkDuplicate($this->mail)) || $oldEmail == $this->mail){
// $sql = 'UPDATE `registration_employs`
// SET `lastname`= :lastname,
// `firstname`= :firstname,
// `address` = :address,
// `birthdate` = :birthdate,
// `telMobile` = :telMobile,
// `telHome` = :telHome,
// `mail` = :mail,
// `remark` = :remark,
// `id_roles` = :id_roles,
// `id_location` = :id_location,
// `id_civility` = :id_civility
// WHERE `id` = :id;';
// $req = $this->pdo->prepare($sql);
// $req->bindValue(':lastname', $this->lastname,PDO::PARAM_STR);
// $req->bindValue(':firstname', $this->firstname,PDO::PARAM_STR);
// $req->bindValue(':address', $this->address,PDO::PARAM_STR);
// $req->bindValue(':birthdate', $this->birthdate,PDO::PARAM_STR);
// $req->bindValue(':telMobile', $this->telMobile,PDO::PARAM_STR);
// $req->bindValue(':telHome', $this->telHome,PDO::PARAM_STR);
// $req->bindValue(':mail', $this->mail,PDO::PARAM_STR);
// $req->bindValue(':remark', $this->remark,PDO::PARAM_STR);
// $req->bindValue(':id_roles', $this->id_roles,PDO::PARAM_INT);
// $req->bindValue(':id_location', $this->id_location,PDO::PARAM_INT);
// $req->bindValue(':id_civility', $this->id_civility,PDO::PARAM_INT);
// $req->bindValue(':id', $this->id,PDO::PARAM_INT);
// try {
// $req->execute();
// if($req->rowCount()!=0){
// // on return les données récupérées
// return 20;
// }
// } catch (PDOException $ex) {
// return 4;
// }
// } else {
// return 21;
// }
// }
// // /*requete maxid*/
// // $recupidmax=$this->pdo->prepare("SELECT max(id) as maxid from `registration_employs`");
// // $varqidmax=array();
// // /* recherche max id */
// // $recupidmax->execute($varqidmax);
// // while($resultmaxid=$recupidmax->fetch())
// // {
// // $maxid=$resultmaxid['maxid'] +1;
// // }
// public function maxID()
// {
// /*requete maxid*/
// $sql = "SELECT max(id) AS id FROM `registration_employs`";
// $recupidmax = $this->pdo->prepare($sql);
// $varqidmax=array();
// /* recherche max id */
// $recupidmax->execute($varqidmax);
// while($resultmaxid=$recupidmax->fetch())
// {
// return $maxid=$resultmaxid->id+1;
// }
// }
}Merci par avance pour votre aide.
@+ Filou