Does not INSERT the data in the database

6

Well folks, I have this code, and what happens is that since I inserted the part to upload an image it does not send anything to the database. Not a new line creates, nothing at all. Can someone 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>
    
asked by anonymous 03.05.2015 / 21:02

1 answer

4

Good morning.

It seems to me that there may be a bug there that causes this problem. Forms with file uploads should have a definition that is missing from this HTML:

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

Then I suggest using the die / echo / print_r to help debug. With these methods it is easy to see whether or not the code of an if is actually being executed.

    
04.05.2015 / 12:47