Does not insert data into database

Asked

Viewed 92 times

6

Good people, I have this code, and the thing is that since I entered the part to upload an image it doesn’t send anything to the database. Not a new line creates, nothing at all. Someone can help me?

<?
    require('../cdn/lib/config.php');

    if(isset($_POST['submit'])){

        if(strlen($_POST['username']) < 3){
            $error[] = 'Username is too short.';
        } else {
            $stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
            $stmt->execute(array(':username' => $_POST['username']));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if(!empty($row['username'])){
                $error[] = 'Username provided is already in use.';
            }
        }

        if(strlen($_POST['password']) < 3){
            $error[] = 'Password is too short.';
        }

        if(strlen($_POST['passwordConfirm']) < 3){
            $error[] = 'Confirm password is too short.';
        }

        if($_POST['password'] != $_POST['passwordConfirm']){
            $error[] = 'Passwords do not match.';
        }

        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $error[] = 'Please enter a valid email address';
        } else {
            $stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
            $stmt->execute(array(':email' => $_POST['email']));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if(!empty($row['email'])){
                $error[] = 'Email provided is already in use.';
            }

        }


        if(!isset($error)){

            // Proteger a password
            $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);

            // Criar código de activação
            $activasion = md5(uniqid(rand(),true));

            try {

        $file       = $_FILES['img'];
        $numFile    = count(array_filter($file['name']));

        //PASTA
        $folder     = 'cdn/uploads/avatars/';

        //REQUISITOS
        $permite    = array('image/jpeg', 'image/png');
        $maxSize    = 1024 * 1024 * 1;

        //MENSAGENS
        $msg        = array();
        $errorMsg   = array(
        1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
        2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
        3 => 'o upload do arquivo foi feito parcialmente',
        4 => 'Não foi feito o upload do arquivo'
            );

    if($numFile <= 0){
        echo '<script>alert(asd);</script>';
    }
    else{
        for($i = 0; $i < $numFile; $i++){
        $name   = $file['name'][$i];
        $type   = $file['type'][$i];
        $size   = $file['size'][$i];
        $error  = $file['error'][$i];
        $tmp    = $file['tmp_name'][$i];

        $extensao = @end(explode('.', $name));
        $avatar = rand().".$extensao";

        if($error != 0)
            $msg[] = "<b>$name :</b> ".$errorMsg[$error];
        else if(!in_array($type, $permite))
            $msg[] = "<b>$name :</b> Erro imagem não suportada!";
        else if($size > $maxSize)
            $msg[] = "<b>$name :</b> Erro imagem ultrapassa o limite de 1MB";
        else{

        if(move_uploaded_file($tmp, $folder.'/'.$avatar)){


                $stmt = $db->prepare('INSERT INTO members (username,password,email,active,avatar) VALUES (:username, :password, :email, :active, :avatar)');
                $stmt->execute(array(
                    ':username' => $_POST['username'],
                    ':password' => $hashedpassword,
                    ':email' => $_POST['email'],
                    ':active' => $activasion,
                    ':avatar' => $avatar
                ));


     }else{
     $msg[] = "<b>$name :</b> Desculpe! Ocorreu um erro...";

       }
      }
     }
     }





















                // Inserir dados na base de dados

                $id = $db->lastInsertId('memberID');

                // Estrutura do email
                $to = $_POST['email'];
                $subject = "Registration Confirmation";
                $body = "Thank you for registering at site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n\n Regards,\n Administration \n\n";
                $additionalheaders = "From: <".SITEEMAIL.">\r\n";
                $additionalheaders .= "Reply-To: $".SITEEMAIL."";
                mail($to, $subject, $body, $additionalheaders);

                header('Location: register.php?action=joined');
                exit;

            } catch(PDOException $e) {
                $error[] = $e->getMessage();
            }

        }

    }
    ?>



        <form role="form" method="post" action="" autocomplete="off">

                    <?php
                    // Verificar erros
                    if(isset($error)){
                        foreach($error as $error){
                            echo '<p class="register-errors">'.$error.'</p>';
                        }
                    }

                    // Mensagem de sucesso
                    if(isset($_GET['action']) && $_GET['action'] == 'joined'){
                        echo "<h2 class='register-sucess'>Registration successful, please check your email to activate your account.</h2> ";
                    }
                    ?>


        <input type="text" name="username" id="username" class="register" placeholder="Username" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1" maxlength="15">

        <br>



          <input type="file" class="register" id="avatar" name="img[]" />
        <br>

        <input type="email" name="email" id="email" class="register" placeholder="Email Address" value="<?php if(isset($error)){ echo $_POST['email']; } ?>" tabindex="2">

        <br>

        <input type="password" name="password" id="password" class="register" placeholder="Password" tabindex="3">

        <br>

        <input type="password" name="passwordConfirm" id="passwordConfirm" class="register" placeholder="Confirm Password" tabindex="4">

        <br>



        <input type="submit" name="submit" class="submit" value="Register" class="register-submit" tabindex="5">

        </form>



    </body>
    </html>
  • 1

    Are you sure it even runs Insert? What is the error message?

  • The problem is even this, mao appears nothing, from SUBMIT and says that it’s okay..

  • Place ini_set('display_errors', true); error_reporting(E_ALL); at the beginning of the code and see which errors appear.

  • no error appears, and yes, I put this at the beginning of the file

  • Is the file after upload being moved to the Cdn/uploads/avatars folder? If it is not, it does not enter INSERT.

  • does not move the image to the folder nor does INSERT of the username, email, avatar, NOTHING..

Show 1 more comment

1 answer

4


Good morning.

It seems to me that there may be an error causing this problem. Forms uploading files must have a definition missing in this HTML:

<form (...) enctype="multipart/form-data">

Then I suggest using the method die / echo / print_r to help debug. With these methods it is easy to see whether or not the code of a given if is actually running.

  • Good morning, solved my problem and I will already give the answer as right! But I have one more error with this code, when it shows the echo "<h2 class='register-sucess'>Registration successful, please check your email to activate your account.</h2> "; also shows the form and was not supposed to :ss

  • @thecreator the way to prevent this from happening is to have an if before showing the form that checks if it is set $_GET['action']. since php redirects to a page with the action parameter when the record is successful, the form should only be shown if that action field is not defined.

  • can you help me? :

  • @thecreator before the form must have: if(!isset($_GET['action'])) { [(...)print form(...)] }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.