I cannot insert data into my database via a php code

epiz_28754132
Link User Area

Error Message

https://infinityfree.net/errors/404/

Other Information

Hello, I cannot insert data into my database via a php code but I manage to use the one that is already there. How to do ? This is for a member’s area.

Perhaps share the code? You also have a redirect error going on, so you might want to share that first.

<?php 
require_once 'config.php'; // On inclu la connexion à la bdd

// Si les variables existent et qu'elles ne sont pas vides
if(!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['cpassword']))
{
    // Patch XSS
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = htmlspecialchars($_POST['password']);
    $cpassword = htmlspecialchars($_POST['cpassword']);

    // On vérifie si l'utilisateur existe
    $check = $bdd->prepare('SELECT username, email, password FROM users WHERE email = ?');
    $check->execute(array($email));
    $data = $check->fetch();
    $row = $check->rowCount();
    
    // On vérifie si le pseudo existe
    $check_psd = $bdd->prepare("SELECT username FROM users WHERE username= ?");
    $check_psd->execute([$username]); 
    $check_username = $check_psd->fetch();

    $email = strtolower($email); // on transforme toute les lettres majuscule en minuscule pour éviter que [email protected] et [email protected] soient deux compte différents ..
    
    // Si la requete renvoie un 0 alors l'utilisateur n'existe pas 
    if($row == 0){ 
        if($check_username == 0){
            if(strlen($email) <= 100){ // On verifie que la longueur du mail <= 100
                if(filter_var($email, FILTER_VALIDATE_EMAIL)){ // Si l'email est de la bonne forme
                    if($password === $cpassword){ // si les deux mdp saisis sont bon

                        // On hash le mot de passe avec Bcrypt, via un coût de 12
                        $cost = ['cost' => 12];
                        $password = password_hash($password, PASSWORD_BCRYPT, $cost);
                        
                        // On stock l'adresse IP
                        $ip = $_SERVER['REMOTE_ADDR']; 

                        // On insère dans la base de données
                        $insert = $bdd->prepare('INSERT INTO users(username, email, password, ip, token) VALUES(:username, :email, :password, :ip, :token)');
                        $insert->execute(array(
                            'username' => $username,
                            'email' => $email,
                            'password' => $password,
                            'ip' => $ip,
                            'token' => bin2hex(openssl_random_pseudo_bytes(64))
                        ));
                        // On redirige avec le message de succès
                        header('Location:inscription.php?reg_err=success');
                        die();
                    }else{ header('Location: inscription.php?reg_err=password'); die();}
                }else{ header('Location: inscription.php?reg_err=email'); die();}
            }else{ header('Location: inscription.php?reg_err=email_length'); die();}
        }else{ header('Location: inscription.php?reg_err=username_already'); die();}
    }else{ header('Location: inscription.php?reg_err=already'); die();}
}

Hey, try to register an account manually from your database and copy the code that is written after you succeed in doing it. That being said, you paste the code into the prepare function and edit the user id to a higher value. Finally, you will need to execute the code once more and see if it succeed in inserting the data into your database.

If the data is inserted in the database then you can change all the necessary information in php, prepare function for example change the username to a variable. Hopefully, it will work.

I had a similar problem and it seemed that PHP in hosting sites is built differently from private hosts such as xampp. Basically, your code is correct but I think it needs to be more specific for the database to read.

1 Like
// On vérifie si l'utilisateur existe
    $check = $bdd->prepare('SELECT username, email, password FROM users WHERE email = ?');
    $check->execute(array($email));
    $data = $check->fetch();
    $row = $check->rowCount();
    
    // On vérifie si le pseudo existe
    $check_psd = $bdd->prepare("SELECT username FROM users WHERE username= ?");
    $check_psd->execute([$username]); 
    $check_username = $check_psd->fetch();

    $email = strtolower($email); // on transforme toute les lettres majuscule en minuscule pour éviter que [email protected] et [email protected] soient deux compte différents ..
    
    // Si la requete renvoie un 0 alors l'utilisateur n'existe pas 
    if($row == 0){ 
        if($check_username == 0){
            if(strlen($email) <= 100){ // On verifie que la longueur du mail <= 100
                if(filter_var($email, FILTER_VALIDATE_EMAIL)){ // Si l'email est de la bonne forme
                    if($password === $cpassword){ // si les deux mdp saisis sont bon

                        // On hash le mot de passe avec Bcrypt, via un coût de 12
                        $cost = ['cost' => 12];
                        $password = password_hash($password, PASSWORD_BCRYPT, $cost);
                        
                        // On stock l'adresse IP
                        $ip = $_SERVER['REMOTE_ADDR']; 

                        // On insère dans la base de données
                        $insert = $bdd->prepare('INSERT INTO users(username, email, password, ip, token) VALUES(:username, :email, :password, :ip, :token)');
                        $insert->execute(array(
                            'username' => $username,
                            'email' => $email,
                            'password' => $password,
                            'ip' => $ip,
                            'token' => bin2hex(openssl_random_pseudo_bytes(64))
                        ));
                        // On redirige avec le message de succès
                        header('Location:inscription.php?reg_err=success');
                        die();
                    }else{ header('Location: inscription.php?reg_err=password'); die();}
                }else{ header('Location: inscription.php?reg_err=email'); die();}
            }else{ header('Location: inscription.php?reg_err=email_length'); die();}
        }else{ header('Location: inscription.php?reg_err=username_already'); die();}
    }else{ header('Location: inscription.php?reg_err=already'); die();}
}

Responder

D3ltaNuub

2d

Ei, tente registrar uma conta manualmente de seu banco de dados e copie o código que é escrito depois de fazer isso. Dito isso, você cola o código na função de preparação e edita o ID do usuário para um valor mais alto. Finalmente, você precisará executar o código mais uma vez e ver se consegue inserir os dados em seu banco de dados.

Se os dados forem inseridos no banco de dados, então você pode alterar todas as informações necessárias no php, função de preparação, por exemplo, alterar o nome de usuário para uma variável. Esperançosamente, funcionará.

Eu tive um problema semelhante e parecia que o PHP em sites de hospedagem é construído de forma diferente de hosts privados como o xampp. Basicamente, seu código está correto, mas acho que precisa ser mais específico para o banco de dados ler.

If you get a 404 error, are you sure the action attribute in the form sends people to the right URL? If the URL there is invalid, people will see a 404 error and the PHP code to process the results is never reached.

I tested the url and I think I’m sure it’s the right one

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.