• User Newbie

    Problema inserimento dati in mysql

    buongiorno a tutti, è il primo post in questo forum.
    premetto che non sono espertissimo di php e ancora meno di interazione con database sql
    ho un problema con un form di registrazione,
    la base del codice è stata presa da un articolo su un sito che parla di php.
    nella versione originale il codice permette di inserire un nuovo record in un db sql, contente username email e password.
    la pagina in php ha i diversi input di testo e vengono passati a uno script php che li elabora e li inserisce nel db

    io ho la necessità di aggiungere altri campi, ma se li aggiungo alla query lo script non funziona, anzi mi blocca l'apertura anche della pagina di inserimento dati, trattandosi di un "include"

    il codice originale dello script che scrive nel db è il seguente:

    codice:

    <?php
    include_once 'db_connect.php';
    include_once 'psl-config.php';

    $error_msg ="";

    if(isset($_POST['username'], $_POST['email'], $_POST['p'])){
    // Sanitize and validate the data passed in
    $username = filter_input(INPUT_POST,'username', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST,'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    // Not a valid email
    $error_msg .='<p class="error">Indirizzo email non valido</p>';
    }

    $password = filter_input(INPUT_POST,'p', FILTER_SANITIZE_STRING);
    **if**(strlen($password)!=128){
        // The hashed pwd should be 128 characters long.
        // If it's not, something really odd has happened
        $error_msg .='<p class="error">Configurazione password errata</p>';
    }
    
    // Username validity and password validity have been checked client side.
    // This should should be adequate as nobody gains any advantage from
    // breaking these rules.
    //
    
    $prep_stmt ="SELECT id FROM members WHERE email = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
    

    // check existing email
    if($stmt){
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();

        **if**($stmt->num_rows ==1){
            // A user with this email address already exists
            $error_msg .='<p class="error">L indirizzo email inserinto risulta registarto</p>';
                        $stmt->close();
        }
                $stmt->close();
    }**else**{
        $error_msg .='<p class="error">Database error Line 39</p>';
                $stmt->close();
    }
    
    // check existing username
    $prep_stmt ="SELECT id FROM members WHERE username = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
    
    **if**($stmt){
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->store_result();
    
                **if**($stmt->num_rows ==1){
                        // A user with this username already exists
                        $error_msg .='<p class="error">Username non disponibile </p>';
    

    $stmt->close();
    }
    $stmt->close();
    }else{
    $error_msg .='<p class="error">Database error line 55</p>';
    $stmt->close();
    }

    // TODO: 
    // We'll also have to account for the situation where the user doesn't have
    // rights to do registration, by checking what type of user is attempting to
    // perform the operation.
    
    **if**(empty($error_msg)){
        // Create a random salt
        //$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE)); // Did not work
        $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()),**true**));
    
        // Create salted password 
        $password = hash('sha512', $password . $random_salt);
    
        // Insert the new user into the database 
        **if**($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")){
            $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
            // Execute the prepared query.
            **if**(! $insert_stmt->execute()){
                header('Location: ../error.php?err=Registration failure: INSERT');
            }
        }
        header('Location: ./regSuccRed.php');
    }
    

    }

    Questo è il codice modificato con l'aggiunta degli altri dati (Carattere piu grande e sottolineato)

    codice:

    <?php
    include_once 'db_connect.php';
    include_once 'psl-config.php';

    $error_msg ="";

    if(isset($_POST['username'], $_POST['email'], $_POST['p'])){
    // Sanitize and validate the data passed in
    $name = filter_input(INPUT_POST,'name', FILTER_SANITIZE_STRING);
    $surname = filter_input(INPUT_POST,'surname', FILTER_SANITIZE_STRING);

    $username = filter_input(INPUT_POST,'username', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST,'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    // Not a valid email
    $error_msg .='<p class="error">Indirizzo email non valido</p>';
    }

    $password = filter_input(INPUT_POST,'p', FILTER_SANITIZE_STRING);
    **if**(strlen($password)!=128){
        // The hashed pwd should be 128 characters long.
        // If it's not, something really odd has happened
        $error_msg .='<p class="error">Configurazione password errata</p>';
    }
    
    // Username validity and password validity have been checked client side.
    // This should should be adequate as nobody gains any advantage from
    // breaking these rules.
    //
    
    $prep_stmt ="SELECT id FROM members WHERE email = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
    

    // check existing email
    if($stmt){
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();

        **if**($stmt->num_rows ==1){
            // A user with this email address already exists
            $error_msg .='<p class="error">L indirizzo email inserinto risulta registarto</p>';
                        $stmt->close();
        }
                $stmt->close();
    }**else**{
        $error_msg .='<p class="error">Database error Line 39</p>';
                $stmt->close();
    }
    
    // check existing username
    $prep_stmt ="SELECT id FROM members WHERE username = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
    
    **if**($stmt){
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->store_result();
    
                **if**($stmt->num_rows ==1){
                        // A user with this username already exists
                        $error_msg .='<p class="error">Username non disponibile </p>';
    

    $stmt->close();
    }
    $stmt->close();
    }else{
    $error_msg .='<p class="error">Database error line 55</p>';
    $stmt->close();
    }

    // TODO: 
    // We'll also have to account for the situation where the user doesn't have
    // rights to do registration, by checking what type of user is attempting to
    // perform the operation.
    
    **if**(empty($error_msg)){
        // Create a random salt
        //$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE)); // Did not work
        $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()),**true**));
    
        // Create salted password 
        $password = hash('sha512', $password . $random_salt);
    
        // Insert the new user into the database 
        **if**($insert_stmt = $mysqli->prepare("INSERT INTO members (*name, surname,* username, email, password, salt) VALUES (*?, ?,* ?, ?, ?, ?)")){
            $insert_stmt->bind_param('ssss',*$name, $surname*, $username, $email, $password, $random_salt);
            // Execute the prepared query.
            **if**(! $insert_stmt->execute()){
                header('Location: ../error.php?err=Registration failure: INSERT');
            }
        }
        header('Location: ./regSuccRed.php');
    }
    

    }

    Naturalmene ho provveduto a modificare la struttura della tabella in questione aggiungendo i campi in pù, è ho chiamato i campi di input della pagina di registrazione nello stesso modo in cui vengono richiamati da questo script

    ho provato anche a fargli eseguire una query di update ma niente da fare, non ne vuole sapere.
    ne sto uscendo pazzo!!! non riesco a capire perchè se aggiungo altri dati non funziona.

    Grazie a tutti
    Pozzo


  • Moderatore

    Quando si modifica uno script di solito si inseriscono i campi aggiuntivi alla fine della tabella non all'inizio. Perchè questo può causare errori nel richiamo della posizione dell'array contenente i dati, prova semplicemente a metterli alla fine e modificare lo script di conseguenza magari il tuo problema è solo questo dato che nel codice non vedo nulla di strano apparte una 20ina di passaggi inutili. La migliore cosa è creare script self-made che usare queste magagne della rete.

    Ciao