How to save form image directory to bank

1

In the system I'm developing it has a form with a field where the user can attach an image.

After saving the form, the user wants to view the record including the image, so I thought about saving the image to a folder on the system and its directory in the database.

This is the page for my form:

<form  method="post" action="update-acidentes.php">
                    <fieldset>
                    <h3 class="subhead" style="color:#39b54a;">Clarificação do problema</h3>
                    <div class="form-field">
                        <h4> O que: </h4>
                        <select style="color:#9e9e9e;" name="OQUE" type="text" id="OQUE" aria-required="true" class="full-width">
                            <option>Clique aqui e selecione...</option>
                            <option>Acidente</option>
                            <option>Quase acidente</option>
                            <option>Trajeto</option>
                            <option>Incêndio</option>
                            <option>Acidente impessoal</option>
                        </select>
                    </div>
                    <h4> Quem </h4>
                    <div class="form-field">
                        <p style="font-size:20px;"> Nome </p>
                        <input style="color:#9e9e9e;" name="NOME" type="text" id="NOME" placeholder="Insira aqui o nome do colaborador" aria-required="true" class="full-width">
                    </div>
                    <div class="form-field">
                        <p style="font-size:20px;"> Descrição do evento </p>
                        <textarea style="color:#9e9e9e;" name="DESCRICAO" type="text" id="DESCRICAO" placeholder="Descreva o ocorrido" aria-required="true" class="full-width"></textarea>
                    </div>
                    <div class="form-field">
                        <p style="font-size:20px;"> Foto </p>
                        <input style="color:#9e9e9e;" name="FOTOA" type="file" id="FOTOA" aria-required="true" class="full-width">
                    </div>
                    <?php require_once('foto-acidente.php'); ?>

                    <div class="form-field">
                        <button type="submit" class="btn btn-primary btn-lg btn-block" style="background-color: #39b54a">Salvar</button>
                    </div>
                    </fieldset>
                </form>

This is the page that saves the form in the database:

<!--Update de acidentes-->
<?php

    $oque        = $_POST['OQUE'];
    $nome        = $_POST['NOME'];
    $descricao   = $_POST['DESCRICAO'];

    $strcon = mysqli_connect('localhost','root','', 'banco') or die('Erro ao conectar ao banco de dados');
    $sql = "INSERT INTO acidentes (OQUE, NOME, DESCRICAO ) VALUES ('$oque', '$nome', '$descricao')"; 
    mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro" . mysqli_error($strcon));
    mysqli_close($strcon);

    if(isset($_FILES["FOTOA"])){
        $arquivo = $_FILES["FOTOA"];
        //diretorio dos arquivos
        $pasta_dir = "images/arquivosACIDENTES/";
        // Faz o upload da imagem
        $arquivo_nome = $pasta_dir . $arquivo["FOTOA"];
        //salva no banco
        move_uploaded_file($arquivo["FOTOA"], $arquivo_nome);

        $query  = "Insert into acidentes (IMAGEM) values ($arquivo_nome)";
    }

    echo '<script type="text/javascript">
            alert("Salvo com Sucesso !");
            window.history.go(-1);
        </script>';

?>

When I save a new record, the saved saved message appears and when I open the database all the columns have been saved except the one in the image.

The folder I created to store the images is also empty.

Does anyone know what might be happening?

    
asked by anonymous 16.08.2018 / 15:50

4 answers

2

In the form tag of the form page you need to include the enctype attribute and set it to "multipart/form-data" which indicates that the form we are using will work with sending files.

<form  method="post" action="update-acidentes.php" enctype="multipart/form-data">

Various errors in the page update-accidents.php

  • Closing the connection before inserting the image into the database
  • The name of the image file is given by% $arquivo = $_FILES['FOTOA']['name'];
  • The directory of the image in the database will be $arquivo_nome = $pasta_dir . $arquivo;
  • The correct syntax for uploading is move_uploaded_file($_FILES["FOTOA"]['tmp_name'], $arquivo_nome);
  • In the insert of the image it is missing the variable $arquivo_nome with single quotation marks
    $query = "Insert into acidentes (IMAGEM) values ('$arquivo_nome')";
  • Failed to execute image query
    mysqli_query($strcon,$query) or die("Erro ao tentar cadastrar imagem" . mysqli_error($strcon));

Code with the correct fixes

<?php

    $oque        = $_POST['OQUE'];
    $nome        = $_POST['NOME'];
    $descricao   = $_POST['DESCRICAO'];
    $arquivo_nome ="";

    $strcon = mysqli_connect('localhost','root','', 'banco') or die('Erro ao conectar ao banco de dados');
    $sql = "INSERT INTO acidentes (OQUE, NOME, DESCRICAO ) VALUES ('$oque', '$nome', '$descricao')"; 
    mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro" . mysqli_error($strcon));

    if(isset($_FILES["FOTOA"])){

        $arquivo = $_FILES['FOTOA']['name'];
        //diretorio dos arquivos
        $pasta_dir = "images/arquivosACIDENTES/";
        // Faz o upload da imagem
        $arquivo_nome = $pasta_dir . $arquivo;
        //salva no banco
        move_uploaded_file($_FILES["FOTOA"]['tmp_name'], $arquivo_nome);

        $query  = "Insert into acidentes (IMAGEM) values ('$arquivo_nome')";
        mysqli_query($strcon,$query) or die("Erro ao tentar cadastrar imagem" . mysqli_error($strcon));
    }

    mysqli_close($strcon);

    echo '<script type="text/javascript">
            alert("Salvo com Sucesso !");
            window.history.go(-1);
        </script>';

?>
  

Note that this script saves in the database as follows:

  

Maybeitwouldbemorepracticaltoinserttheimageonthesameline

  

Inthiscasethepageupdate-accidents.phpwouldbe

<?php$oque=$_POST['OQUE'];$nome=$_POST['NOME'];$descricao=$_POST['DESCRICAO'];if(isset($_FILES["FOTOA"])){

        $arquivo = $_FILES['FOTOA']['name'];
        //diretorio dos arquivos
        $pasta_dir = "images/arquivosACIDENTES/";
        // Faz o upload da imagem
        $arquivo_nome = $pasta_dir . $arquivo;
        //salva no banco
        move_uploaded_file($_FILES["FOTOA"]['tmp_name'], $arquivo_nome);

    /**************  registro no banco de dados ******************/ 
    $strcon = mysqli_connect('localhost','root','', 'banco') or die('Erro ao conectar ao banco de dados');
    $sql = "INSERT INTO acidentes (OQUE, NOME, DESCRICAO, IMAGEM ) VALUES ('$oque', '$nome', '$descricao', '$arquivo_nome')"; 
    mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro" . mysqli_error($strcon));

    mysqli_close($strcon);
   /**************** fim registro no banco de dados *************/

    }

    echo '<script type="text/javascript">
            alert("Salvo com Sucesso !");
            window.history.go(-1);
        </script>';

?>
  

If the image is not mandatory, simply pass the record lines in the database after the conditional closing if

    
17.08.2018 / 04:53
2

Good first of all, if you are using a local server , like xampp for example, you need to leave the folder with the images in the same folder as the server, because it can not access the files externally.

Second in your form you need to add the enctype tag, because it allows you to get the value of the photo path through $ _FILES add that in the code

<form  method="post" action="update-acidentes.php" enctype="multipart/form-data">

I hope I have helped, we are all there

    
16.08.2018 / 18:36
1

The error is that you try to use $arquivo["FOTOA"] as if it were the name of the file. He is not. This index does not even exist. You're probably getting an error like this:

  

Notice: Undefined index: FOTOA in ...

The right thing to do is to use this:

    $arquivo_nome = $pasta_dir . $arquivo["name"];
    // envia o arquivo temporário para o diretório
    move_uploaded_file($arquivo["tmp_name"], $arquivo_nome);

In addition to Alvaro Leandro has been quoted that his form has to look like this:

<form  method="post" action="update-acidentes.php" enctype="multipart/form-data">
    
17.08.2018 / 01:23
1

Come on,

  

1) In the Form tag add the enctype="multipart / form-data" property. Home   2) Check the field that receives the image in the database, whether it is a char or varchar of considerable size. Home   3) in place of '/' in the directory of the file, use the php DIRECTORY_SEPARATOR constant, eg: "images" .DIRECTORY_SEPARATOR. "ACCIDENT files" .DIRECTORY_SEPARATOR "

    
16.08.2018 / 18:38