non duplicare dati in stato "aggiornamento"

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
Salve, ho questo codice scritto dai vari tutorial che leggo.. Vorrei sapere per far che l'utente quando modifica l'email non deve andare ad duplicare la email di un altro utente .. cosa devo fare?, grazie mille.

Grazie mille.

codice:


PHP:
<?php
session_start();
require 'inc.php';
require 'admin.php';

$db = getDB();

$message = '';


if(isset($_POST["submit"]))
{
    $name = cleanInput($_POST["name"]);
    $surname = cleanInput($_POST["surname"]);
    $birthday = cleanInput($_POST["birthday"]);
    $sex = cleanInput($_POST["sex"]);
    $username = cleanInput($_POST["username"]);
    $password = cleanInput($_POST["password"]);
    $email = cleanInput($_POST["email"]);
    if(empty($name))
    {
        $message = "Inserire il nome";
    }else
    if(empty($surname))
    {
        $message = "Inserire il cognome";
    }else
    if(empty($birthday))
    {
        $message = "Inserire la data di nascita";
    }
    else if(empty($username))
    {
            $message = "Inserire l'username";
    }else if(empty($email))
    {
            $message = "Inserire l'email";
    }

    else if(empty($password))
    {
        $message = "Inserire la password";
    }


    else {

            $age = date_diff(date_create($birthday), date_create('now'))->y;


            $sql = "UPDATE users SET  name=:name, surname=:surname, description=:description, slug=:slug, picture=:picture, birthday=:birthday, age=:age, sex=:sex, username=:username, password=:password, email=:email, isLevel=:isLevel, date_reg=:date_reg WHERE id=:id";


            $stmt = $db->prepare($sql);
            $stmt->bindParam(':name', $name, PDO::PARAM_STR);
            $stmt->bindParam(':surname', $surname, PDO::PARAM_STR);
            $description = '';
            $stmt->bindParam(':description', $description, PDO::PARAM_STR);
            $stmt->bindParam(':slug', $username, PDO::PARAM_STR);
            $pic = '';
            $stmt->bindParam(':picture', $pic, PDO::PARAM_STR);
            $stmt->bindParam(':birthday', $birthday, PDO::PARAM_STR);
            $stmt->bindParam(':age', $age, PDO::PARAM_INT);
            $stmt->bindParam(':sex', $sex, PDO::PARAM_STR);
          $stmt->bindParam(':username', $username, PDO::PARAM_STR);
            $pwd = password_hash($password, PASSWORD_BCRYPT);
            $stmt->bindParam(':password', $pwd);
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $isLevel = 1;
            $stmt->bindParam(':isLevel', $isLevel, PDO::PARAM_INT);
            $date = date('Y-m-d H:i:s');
            $stmt->bindParam(':date_reg', $date, PDO::PARAM_STR);
            $stmt->bindValue(':id', $_SESSION['user_id']);
            if( $stmt->execute() ):
                $message = 'Aggiornato';
            else:
                $message = "Problema nella creazione del'account";
            endif;

    }

}
require 'theme/header-admin.php';

$records = $db->prepare('SELECT * FROM users WHERE id = :id');
$records->bindValue(':id', $_SESSION['user_id']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);

$user = NULL;

if( count($results) > 0){
$user = $results;
}
?>
    <?php if(!empty($message)): ?>
        <p><?= $message ?></p>
    <?php endif; ?>

    <h1>Aggiorna</h1>
    <span>or <a href="login.php">login</a></span>

    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
        Nome: <input type="text"  name="name" value="<?php echo $user['name']; ?>">
        Cognome: <input type="text"  name="surname" value="<?php echo $user['surname']; ?>">
        Birthday: <input type="date"  name="birthday" value="<?php echo $user['birthday']; ?>">
        Sex:
        <?php
        $sex = $user["sex"];
        ?>
    <p><select name="sex" class="form-control">
     <option value="M" <?php if ($sex == "M") echo ' selected' ?>>Maschio</option>
     <option value="F" <?php if ($sex == "F") echo ' selected' ?>>Femmina</option>
   </select>
         </p>
        Username:
        <input type="username" name="username" value="<?php echo $user['username']; ?>">
Password:
        <input type="password" name="password">
Email:
        <input type="email"  name="email" value="<?php echo $user['email']; ?>">
        <input type="submit" name="submit">
    </form>

<?php
require 'theme/footer-admin.php';
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
Salve, seconda versione con le api di pdo errorinfo. ma non so non mi stampa nulla. vi posto il codice se mi potete aiutarmi.
PHP:
<?php
session_start();
require 'inc.php';
require 'admin.php';

$db = getDB();

$message = '';


if(isset($_POST["submit"]))
{
    $name = cleanInput($_POST["name"]);
    $surname = cleanInput($_POST["surname"]);
    $birthday = cleanInput($_POST["birthday"]);
    $sex = cleanInput($_POST["sex"]);
    $password = cleanInput($_POST["password"]);
    $email = cleanInput($_POST["email"]);
    if(empty($name))
    {
        $message = "Inserire il nome";
    }else
    if(empty($surname))
    {
        $message = "Inserire il cognome";
    }else
    if(empty($birthday))
    {
        $message = "Inserire la data di nascita";
    }else if(empty($email))
    {
            $message = "Inserire l'email";
    }

    else if(empty($password))
    {
        $message = "Inserire la password";
    }
    else {


        $already_exists = true;
        $stmt = $db->prepare("SELECT id FROM email WHERE email = :email");
        $stmt->execute(array(':email' => $email));
        if ($stmt->rowCount() > 0) {
            $already_exists = false;
        }
        else {
            try {

                        $age = date_diff(date_create($birthday), date_create('now'))->y;
                        $sql = "UPDATE users SET  name=:name, surname=:surname, description=:description, slug=:slug, picture=:picture, birthday=:birthday, age=:age, sex=:sex, password=:password, email=:email, isLevel=:isLevel, date_reg=:date_reg WHERE id=:id";

                        $stmt = $db->prepare($sql);
                        $stmt->bindParam(':name', $name, PDO::PARAM_STR);
                        $stmt->bindParam(':surname', $surname, PDO::PARAM_STR);
                        $description = '';
                        $stmt->bindParam(':description', $description, PDO::PARAM_STR);
                        $stmt->bindParam(':slug', $username, PDO::PARAM_STR);
                        $pic = '';
                        $stmt->bindParam(':picture', $pic, PDO::PARAM_STR);
                        $stmt->bindParam(':birthday', $birthday, PDO::PARAM_STR);
                        $stmt->bindParam(':age', $age, PDO::PARAM_INT);
                        $stmt->bindParam(':sex', $sex, PDO::PARAM_STR);
                        $pwd = password_hash($password, PASSWORD_BCRYPT);
                        $stmt->bindParam(':password', $pwd);
                        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
                        $isLevel = 1;
                        $stmt->bindParam(':isLevel', $isLevel, PDO::PARAM_INT);
                        $date = date('Y-m-d H:i:s');
                        $stmt->bindParam(':date_reg', $date, PDO::PARAM_STR);
                        $stmt->bindValue(':id', $_SESSION['user_id']);
                        $stmt->execute();
            } catch (PDOException $e) {
                if ($e->errorInfo[1] == 1062) {
                    $already_exists = false;
                } else {
                    throw $e;
                }
            }
        }





try {
            $stmt->execute();
            $message = "Aggiornato";
        } catch (PDOException $e) {
           if ($e->errorInfo[1] == 1062) {
                    $message = "Il dato esiste gi&agrave;";
           } else {

           }
        }
    }

}
require 'theme/header-admin.php';

$records = $db->prepare('SELECT * FROM users WHERE id = :id');
$records->bindValue(':id', $_SESSION['user_id']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);

$user = NULL;

if( count($results) > 0){
$user = $results;
}
?>
    <?php if(!empty($message)): ?>
        <p><?= $message ?></p>
    <?php endif; ?>

    <h1>Aggiorna</h1>
    <span>or <a href="login.php">login here</a></span>

    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
        Nome: <input type="text"  name="name" value="<?php echo $user['name']; ?>">
        Cognome: <input type="text"  name="surname" value="<?php echo $user['surname']; ?>">
        Birthday: <input type="date"  name="birthday" value="<?php echo $user['birthday']; ?>">
        Sex:
        <?php
        $sex = $user["sex"];
        ?>
    <p><select name="sex" class="form-control">
     <option value="M" <?php if ($sex == "M") echo ' selected' ?>>Maschio</option>
     <option value="F" <?php if ($sex == "F") echo ' selected' ?>>Femmina</option>
   </select>
         </p>
Password:
        <input type="password" name="password">
Email:
        <input type="email"  name="email" value="<?php echo $user['email']; ?>">
        <input type="submit" name="submit">
    </form>

<?php
require 'theme/footer-admin.php';
 

Tommy03

Utente Attivo
6 Giu 2018
616
58
28
20
Vicenza
Non ti viene nessun errore?
Se il codice lo hai copiato un po' qua e là, ti consiglio di mettere degli echo dentro al codice php in modo da capire dove sta l'errore. Tipo prova così e poi dicci quali messaggi ti vengono fuori:
PHP:
<?php
session_start();
require 'inc.php';
require 'admin.php';

$db = getDB();

$message = '';


if(isset($_POST["submit"]))
{
echo "ok <br>";
$name = cleanInput($_POST["name"]);
$surname = cleanInput($_POST["surname"]);
$birthday = cleanInput($_POST["birthday"]);
$sex = cleanInput($_POST["sex"]);
$username = cleanInput($_POST["username"]);
$password = cleanInput($_POST["password"]);
$email = cleanInput($_POST["email"]);
if(empty($name)){
$message = "Inserire il nome";
}elseif(empty($surname)){
$message = "Inserire il cognome";
}elseif(empty($birthday)){
$message = "Inserire la data di nascita";
}elseif(empty($username)){
$message = "Inserire l'username";
}elseif(empty($email)){
$message = "Inserire l'email";
}elseif(empty($password)){
$message = "Inserire la password";
}
else {
echo "no errori <br>";
$age = date_diff(date_create($birthday), date_create('now'))->y;


$sql = "UPDATE users SET name=:name, surname=:surname, description=:description, slug=:slug, picture=:picture, birthday=:birthday, age=:age, sex=:sex, username=:username, password=:password, email=:email, isLevel=:isLevel, date_reg=:date_reg WHERE id=:id";


$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':surname', $surname, PDO::PARAM_STR);
$description = '';
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->bindParam(':slug', $username, PDO::PARAM_STR);
$pic = '';
$stmt->bindParam(':picture', $pic, PDO::PARAM_STR);
$stmt->bindParam(':birthday', $birthday, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->bindParam(':sex', $sex, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$pwd = password_hash($password, PASSWORD_BCRYPT);
$stmt->bindParam(':password', $pwd);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$isLevel = 1;
$stmt->bindParam(':isLevel', $isLevel, PDO::PARAM_INT);
$date = date('Y-m-d H:i:s');
$stmt->bindParam(':date_reg', $date, PDO::PARAM_STR);
$stmt->bindValue(':id', $_SESSION['user_id']);
if( $stmt->execute() ){
echo "query ok <br>";
$message = 'Aggiornato';
}else{
echo "errore nella query <br>";
$message = "Problema nella creazione del'account";
}

}

}
require 'theme/header-admin.php';

$records = $db->prepare('SELECT * FROM users WHERE id = :id');
$records->bindValue(':id', $_SESSION['user_id']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);

$user = NULL;

if( count($results) > 0){
$user = $results;
}
?>
    <?php if(!empty($message)): ?>
        <p><?= $message ?></p>
    <?php endif; ?>

    <h1>Aggiorna</h1>
    <span>or <a href="login.php">login</a></span>

    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
        Nome: <input type="text"  name="name" value="<?php echo $user['name']; ?>">
        Cognome: <input type="text"  name="surname" value="<?php echo $user['surname']; ?>">
        Birthday: <input type="date"  name="birthday" value="<?php echo $user['birthday']; ?>">
        Sex:
        <?php
        $sex = $user["sex"];
?>
    <p><select name="sex" class="form-control">
     <option value="M" <?php if ($user['sex'] == "M") echo ' selected' ?>>Maschio</option>
     <option value="F" <?php if ($user['sex'] == "F") echo ' selected' ?>>Femmina</option>
   </select>
         </p>
        Username:
        <input type="username" name="username" value="<?php echo $user['username']; ?>">
Password:
        <input type="password" name="password">
Email:
        <input type="email"  name="email" value="<?php echo $user['email']; ?>">
        <input type="submit" name="submit">
    </form>

<?php
require 'theme/footer-admin.php';
P.S. la connessione sei sicuro che funzioni? Hai mai provato ad eseguire altre query?
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
Salve, non so se è giusto gestire gli errorInfo, di pdo . dimmi se va bene cosi. perché in questo modo funziona. Ma non sono sicuro se va bene gestire gli errorInfo di Pdo. grazie mille.
PHP:
<?php

session_start();

require 'inc.php';

require 'admin.php';



$db = getDB();



$message = '';





if(isset($_POST["submit"]))

{

    $name = cleanInput($_POST["name"]);

    $surname = cleanInput($_POST["surname"]);

    $birthday = cleanInput($_POST["birthday"]);

    $sex = cleanInput($_POST["sex"]);

    $password = cleanInput($_POST["password"]);

    $email = cleanInput($_POST["email"]);

    if(empty($name))

    {

        $message = "Inserire il nome";

    }else

    if(empty($surname))

    {

        $message = "Inserire il cognome";

    }else

    if(empty($birthday))

    {

        $message = "Inserire la data di nascita";

    }else if(empty($email))

    {

            $message = "Inserire l'email";

    }



    else if(empty($password))

    {

        $message = "Inserire la password";

    }

    else {





                        $age = date_diff(date_create($birthday), date_create('now'))->y;

                        $sql = "UPDATE users SET  name=:name, surname=:surname, description=:description, picture=:picture, birthday=:birthday, age=:age, sex=:sex, password=:password, email=:email, date_reg=:date_reg WHERE id=:id";



                        $stmt = $db->prepare($sql);

                        $stmt->bindParam(':name', $name, PDO::PARAM_STR);

                        $stmt->bindParam(':surname', $surname, PDO::PARAM_STR);

                        $description = '';

                        $stmt->bindParam(':description', $description, PDO::PARAM_STR);

                        $pic = '';

                        $stmt->bindParam(':picture', $pic, PDO::PARAM_STR);

                        $stmt->bindParam(':birthday', $birthday, PDO::PARAM_STR);

                        $stmt->bindParam(':age', $age, PDO::PARAM_INT);

                        $stmt->bindParam(':sex', $sex, PDO::PARAM_STR);

                        $pwd = password_hash($password, PASSWORD_BCRYPT);

                        $stmt->bindParam(':password', $pwd);

                        $stmt->bindParam(':email', $email, PDO::PARAM_STR);

                        $date = date('Y-m-d H:i:s');

                        $stmt->bindParam(':date_reg', $date, PDO::PARAM_STR);

                        $stmt->bindValue(':id', $_SESSION['user_id']);



         if (!$stmt->execute())

         {

             $err = $stmt->errorInfo();

             if (isset($err[1]))

             {

                 if ($err[1] == 1062)

                     $message =  'This email already exists.';

             }

         }

        }

}



require 'theme/header-admin.php';



$records = $db->prepare('SELECT * FROM users WHERE id = :id');

$records->bindValue(':id', $_SESSION['user_id']);

$records->execute();

$results = $records->fetch(PDO::FETCH_ASSOC);



$user = NULL;



if( count($results) > 0){

$user = $results;

}

?>

    <?php if(!empty($message)): ?>

        <p><?= $message ?></p>

    <?php endif; ?>



    <h1>Aggiorna</h1>



    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">

        Nome: <input type="text"  name="name" value="<?php echo $user['name']; ?>">

        Cognome: <input type="text"  name="surname" value="<?php echo $user['surname']; ?>">

        Birthday: <input type="date"  name="birthday" value="<?php echo $user['birthday']; ?>">

        Sex:

        <?php

        $sex = $user["sex"];

        ?>

    <p><select name="sex" class="form-control">

     <option value="M" <?php if ($sex == "M") echo ' selected' ?>>Maschio</option>

     <option value="F" <?php if ($sex == "F") echo ' selected' ?>>Femmina</option>

   </select>

         </p>

Password:

        <input type="password" name="password">

Email:

        <input type="email"  name="email" value="<?php echo $user['email']; ?>">

        <input type="submit" name="submit">

    </form>



<?php

require 'theme/footer-admin.php';
 

Tommy03

Utente Attivo
6 Giu 2018
616
58
28
20
Vicenza
Non saprei mi dispiace... Prova a vedere online se trovi qualcosa, ma comunque se funziona io lascerei così
 

macus_adi

Utente Attivo
5 Dic 2017
1.343
91
48
IT/SW
sta per i duplicate entry. ora cerco in inglese su google. grazie mille.
Ciao, scusa non sarebbe più logico effettuare una query con ID ed Email attuale utente e dal modello effettui l'update?

PHP:
$user=MyModel::instanceOfModel()->find($_SESSION['user_id']);

$fEmail=MyModel::instenceOfModel()->whereEmail($email);

if(null===$fEmail){
array_walk($_POST,function($v,$k) use (&$user){
    $user->$k=cleanInput($v);
});
$user->save();

}else{
//Email già presente
}
 
Discussioni simili
Autore Titolo Forum Risposte Data
felino Mac OS e Client Mail: Stato non in linea Mac e Software 1
I nome utente non esiste nel database PHP 1
M Drag and Drop non capisco le sequenze... Javascript 1
L Suggerimento Pagespeed per non vedenti HTML e CSS 0
F comando di inclusione file audio in I-Pad non funziona HTML e CSS 1
M Immagini non usate WordPress 0
B Non riesco a trovare i cognomi con i caratteri speciali in Access (Microsoft 365) MS Access 0
G Numero zero null non deve visualizzare nulla PHP 0
F Paypal _xclick IPN non risponde PHP 1
R Variabile non risconosciuta dentro una funzione PHP 1
C ACCESS Aprire maschera se valore non presente in una combo MS Access 7
E Alert non viene mostrato PHP 1
felino Hardisk WD SATA 1TB 3.5" non si avvia! Hardware 4
K Scrip non funzionante Javascript 1
R jquery che cambia css di un elemento non mi funziona sulla pagina caricata da ajax Ajax 5
zorro CREATE TABLE non funziona PHP 6
L tipo boolean non funzionante su mariadb (mysql). E codice php 7.4. PHP 0
Sevenjeak Php8 non carica estenzioni PHP 0
R query DELETE non cancella i record PHP 1
otto9due Input text: accetta solo numeri e non può essere vuoto. Javascript 9
G Non vedo frecce su forme Photoshop 2
G Il mio sito dopo aver abilitato l'ssl non visualizza le immagini con indirizzi senza ssl HTML e CSS 0
P jquery refresh div non funziona Javascript 0
N Problema SEO "L'URL non si trova su Google" SEO e Posizionamento 4
S Certificato SSL non funzionante Domini 0
zorro modulo di registrazione: funziona ma non sempre PHP 2
D Form contatti non funzionante HTML e CSS 0
MarcoGrazia Trovare record nel database partendo da id non sequenziali PHP 6
M Non ho rinnovato il mio sito su Aruba... Domini 1
T IP INFO NON FUNZIONA PHP 0
Shyson Google search non trova il mio sito SEO e Posizionamento 1
E Estrarre dati da doppia tabella, banale ma non sempre PHP 1
P Data scraping in PHP non funziona PHP 4
otto9due $_FILE non passa i dati dal form PHP 1
keyascii Non è mai troppo tardi Presentati al Forum 0
N dati tabella non presi PHP 1
P Pagina modifica record che non funziona PHP 0
Shyson AUTO_INCREMENT non si aggiorna MySQL 2
Shyson Codice wp-login non funziona PHP 2
S WORDPRESS NON FA INSTALLARE PIU NULLA WordPress 9
Shyson Non mi fa accedere al sito WordPress 12
N Non Autorizzato. Dovresti rimuovere il parametro customize_messenger_channel per visualizzare l'anteprima in frontend. WordPress 1
R INSERT INTO tabella non funziona Classic ASP 2
A Problema, non so, di scale() o transform, oppure altro? HTML e CSS 0
felino Conversione da MPG a MP4: audio non sincronizzato Windows e Software 1
F Telecamere Wi-Fi non si connettono A nvr IP Cam e Videosorveglianza 0
G Finestra di dialogo che non si apre - programma NUENDO Windows e Software 0
L php mysql non salva solo id PHP 21
D Pagina non trovata Wordpress WordPress 7
S connesso, internet non disponibile ( con extebder tp-link850) Reti LAN e Wireless 0

Discussioni simili