Bug when doing INSERT in database with PHP and Mysql

Asked

Viewed 70 times

0

I have an INSERT script that even not selecting any image within another input, in the database saves the name of the image formatted by the Rand function but without any extension, instead of being empty.

<?php
session_start();
    require_once "classes/conexao.php";
    require_once "classes/logar.php";
    ini_set('default_charset','utf-8');
    require_once 'dbconfig.php';

    if(isset($_GET['logout'])):

        if($_GET['logout']== 'ok'):
           Login::deslogar();

    endif;

endif;
error_reporting( ~E_NOTICE ); // avoid notice
    if(isset($_POST['btnsave']))
    {
        $titulo = $_POST['titulo'];
        $sub_titulo = $_POST['sub_titulo'];
        $texto_1 = $_POST['texto_1'];
        $texto_2 = $_POST['texto_2'];
        $texto_3 = $_POST['texto_3'];
        $texto_4 = $_POST['texto_4'];
        $categoria_1 = $_POST['categoria_1'];
        $categoria_2 = $_POST['categoria_2'];
        $categoria_3 = $_POST['categoria_3'];
        $autor = $_POST['autor'];

        $imgFile = $_FILES['user_image']['name'];
        $tmp_dir = $_FILES['user_image']['tmp_name'];
        $imgSize = $_FILES['user_image']['size'];

        $imgFile2 = $_FILES['user_image2']['name'];
        $tmp_dir2 = $_FILES['user_image2']['tmp_name'];
        $imgSize2 = $_FILES['user_image2']['size'];

        $imgFile3 = $_FILES['user_image3']['name'];
        $tmp_dir3 = $_FILES['user_image3']['tmp_name'];
        $imgSize3 = $_FILES['user_image3']['size'];

        if(empty($titulo)){
            $errMSG = "Por favor Insira o Titulo";
        }

        else if(empty($imgFile)){
            $errMSG = "Selecione a imagem.";
        }
        else
        {
            $upload_dir = 'img/'; // upload directory

            $imgExt =  strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
            $imgExt2 = strtolower(pathinfo($imgFile2,PATHINFO_EXTENSION));
            $imgExt3 = strtolower(pathinfo($imgFile3,PATHINFO_EXTENSION));


            $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

            // rename uploading image
      $userpic = rand(1000,1000000).".".$imgExt;
            $userpic2 = rand(1000,1000000).".".$imgExt2;
            $userpic3 = rand(1000,1000000).".".$imgExt3;


            // allow valid image file formats
            if(in_array($imgExt, $valid_extensions)){           
                // Check file size '5MB'
                if($imgSize < 5000000)              {
                    move_uploaded_file($tmp_dir,$upload_dir.$userpic);
                }
                else{
                    $errMSG = "Imagem muito grande.";
                }
            }
            else{

            }
            if(in_array($imgExt2, $valid_extensions)){          
                // Check file size '5MB'
                if($imgSize2 < 5000000)             {
                    move_uploaded_file($tmp_dir2,$upload_dir.$userpic2);
                }
                else{
                    $errMSG = "Banner muito grande.";
                }
            }
            else{

            }
            if(in_array($imgExt3, $valid_extensions)){          
                // Check file size '5MB'
                if($imgSize3 < 5000000)             {
                    move_uploaded_file($tmp_dir3,$upload_dir.$userpic3);
                }
                else{
                    $errMSG = "IMAGEM 3 muito grande.";
                }
            }
            else{

            }

        }
        if(!isset($errMSG))
        {
            $stmt = $DB_con->prepare('INSERT INTO posts (titulo,sub_titulo,texto_1,texto_2,texto_3,texto_4,categoria_1,categoria_2,categoria_3,autor,img1,img2,img3) VALUES(:utitulo,:usub_titulo,:utexto_1,:utexto_2,:utexto_3,:utexto_4,:ucategoria_1,:ucategoria_2,:ucategoria_3,:uautor,:upic,:upic2, :upic3)');
            $stmt->bindParam(':utitulo',$titulo);
            $stmt->bindParam(':usub_titulo',$sub_titulo);
            $stmt->bindParam(':utexto_1',$texto_1);
            $stmt->bindParam(':utexto_2',$texto_2);
            $stmt->bindParam(':utexto_3',$texto_3);
            $stmt->bindParam(':utexto_4',$texto_4);
            $stmt->bindParam(':ucategoria_1',$categoria_1);
            $stmt->bindParam(':ucategoria_2',$categoria_2);
            $stmt->bindParam(':ucategoria_3',$categoria_3);
            $stmt->bindParam(':uautor',$autor);
            $stmt->bindParam(':upic',$userpic);
            $stmt->bindParam(':upic2',$userpic2);
            $stmt->bindParam(':upic3',$userpic3);

            if($stmt->execute())
            {
                $successMSG = "Post adicionada com sucesso ...";
                header("refresh:3;painel_posts.php"); // redirects image view page after 5 seconds.
            }
            else
            {
                $errMSG = "error while inserting....";
            }
        }
    }

if(isset($_SESSION['logado'])):
else:
    header("Location: login.php");
endif;
?>
<!DOCTYPE html>
<html lang="pt-br">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="cairoodev">

  <title>Adicionar Post</title>

  <!-- Custom fonts for this template-->
  <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

  <!-- Custom styles for this template-->
  <link href="css/sb-admin-2.css" rel="stylesheet">

</head>

<body id="page-top">

  <!-- Page Wrapper -->
  <div id="wrapper">
  <?php
    include "nav_admin.php";
  ?>

        <!-- Begin Page Content -->
        <div class="container-fluid">

          <!-- Page Heading -->
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Adicionar novo Post</h1>

          </div>
          <?php
    if(isset($errMSG)){
            ?>
            <div class="alert alert-danger">
                <span class="glyphicon glyphicon-info-sign"></span> <strong><?php echo $errMSG; ?></strong>
            </div>
            <?php
    }
    else if(isset($successMSG)){
        ?>
        <div class="alert alert-success">
              <strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
        </div>
        <?php
    }
    ?>
        <form method="post" enctype="multipart/form-data" class="form-horizontal">
        <div class="row">
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-6">
                        <label class="control-label">Titulo</label>
                        <input class="form-control" type="text" name="titulo" placeholder="Titulo do post" value="<?php echo $titulo; ?>" />
                     </div>
                     <div class="col-md-6">
                        <label class="control-label">Sub Titulo</label>
                        <input class="form-control" type="text" name="sub_titulo" placeholder="Sub Titulo do post" value="<?php echo $sub_titulo; ?>" />
                     </div>
                </div>
                <label class="control-label">Imagem Principal</label>
                <input class="input-group" type="file" name="user_image" accept="image/*" />
                <div class="row">
                    <div class="col-md-6">
                        <label class="control-label">Texto 1</label>
                        <textarea class="form-control" type="text" name="texto_1" placeholder="Texto de introdução" value="<?php echo $texto_1; ?>" /></textarea>
                     </div>
                     <div class="col-md-6">
                        <label class="control-label">Texto 2</label>
                        <textarea class="form-control" type="text" name="texto_2" placeholder="Texto de desenvolvimento" value="<?php echo $texto_2; ?>" /></textarea>   
                     </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <label class="control-label">Texto 3</label>
                        <textarea class="form-control" type="text" name="texto_3" placeholder="Texto de desenvolvimento 2" value="<?php echo $texto_3; ?>" /></textarea>
                     </div>
                     <div class="col-md-6">
                     <label class="control-label">Texto 4</label>
                        <textarea class="form-control" type="text" name="texto_4" placeholder="Texto de conclusão" value="<?php echo $texto_4; ?>" /></textarea>
                     </div>
                </div>  
            </div>
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-6">
                        <label class="control-label">Imagem 2</label>
                        <input class="input-group" type="file" name="user_image2" accept="image/*" />
                    </div>
                    <div class="col-md-6">
                        <label class="control-label">Imagem 3</label>
                        <input class="input-group" type="file" name="user_image3" accept="image/*" />
                    </div>
                </div>
                <label class="control-label">Categorias</label>
                <div class="row">

                    <div class="col-md-4">

                        <input class="form-control" type="text" name="categoria_1" placeholder="Categoria 1" value="<?php echo $categoria_1; ?>"/>
                    </div>
                    <div class="col-md-4">

                        <input class="form-control" type="text" name="categoria_2" placeholder="Categoria 2" value="<?php echo $categoria_2; ?>"/>
                    </div>
                    <div class="col-md-4">

                        <input class="form-control" type="text" name="categoria_3" placeholder="Categoria 3" value="<?php echo $categoria_3; ?>"/>
                    </div>

                </div>
                <input class="form-control" type="hidden" name="autor" placeholder="Autor" value="<?php echo $_SESSION['nome'];?>"/>
            </div>
</div><br>
        <button type="submit" name="btnsave" class="btn btn-primary shadow-sm">
        <span class="glyphicon glyphicon-save"></span><i class="fas fa-download fa-sm text-white-50"></i> Postar
        </button>
    </form> 

          <!-- Content Row -- >

      </div>
      <!-- End of Main Content -->

      <!-- Footer -->
      <footer class="sticky-footer bg-white">
        <div class="container my-auto">
          <div class="copyright text-center my-auto">
            <span>Copyright &copy; Your Website 2019</span>
          </div>
        </div>
      </footer>
      <!-- End of Footer -->

    </div>
    <!-- End of Content Wrapper -->

  </div>
  <!-- End of Page Wrapper -->

  <!-- Scroll to Top Button-->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <!-- Logout Modal-->
  <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
          <button class="close" type="button" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
        <div class="modal-footer">
          <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
          <a class="btn btn-primary" href="login.html">Logout</a>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

In this code when I select Image 1 only, in the database it looks like this.

Banco de Dados

inside the img2 and img3 columns instead of being NULL or empty, it gets the value of the converted image name and inserts it into the database without the extensions.

Wanted help on how to fix this and when I insert only one image the other image fields does not assign any value.

1 answer

1

Before doing the treatments of each image check if it exists.

In the first image you check this, but not in the other two. Else if(Empty($imgFile)){ $errMSG = "Select image."; }

Abs.

Browser other questions tagged

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