How to save form image directory in the database

Asked

Viewed 1,283 times

0

In the system I am developing 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 in a folder on the system and its directory in the database.

That’s my form page:

<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 bank:

<!--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 message appears successfully and when I open the database really all the columns were saved except the image.

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

Does anyone know what might be going on?

4 answers

3


Tag form form page you need to include attribute enctype and define how "multipart/form-data" which indicates that the form we are using will work with uploading files.

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

Several errors in the update-accidents.php page

  • Closing the connection before the image Insert in the bank
  • The image file name is given by
    $arquivo = $_FILES['FOTOA']['name'];
  • The image directory in the database will be
    $arquivo_nome = $pasta_dir . $arquivo;
  • The correct upload syntax is
    move_uploaded_file($_FILES["FOTOA"]['tmp_name'], $arquivo_nome);
  • In the image index missing involve the variable $arquivo_nome with single quotes
    $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 appropriate corrections

<?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 is saved in the bank as follows:

inserir a descrição da imagem aqui

Perhaps it would be more practical to insert the image in the same line

inserir a descrição da imagem aqui

In this case the update-accidents.php page would be

<?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, just pass the lines of the record in the database after the closure of the conditional if

  • Perfect. Very explanatory, solved the problem. Thank you.

2

good first of all, if you are using a local server, like xampp for example, it is necessary to leave the folder with the images in the same server folder, as it cannot access the files externally.

Second on your form you need to add the enctype tag, as it allows you to pick up the value of the photo path through $_FILES add this in the code

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

I hope I’ve helped, anything we’re there

  • Then, the image folder is inside the system folder itself that is inside the Easyphp folder. I tried to put the enctype as suggested but nothing happened. :(

  • 1

    Recently I made a system to insert the path in the database, my code is like $photo = $_FILES["photo"]; if(!Empty($photo["name"])) $dir = "Profile Photo/"; $filename = $dir . $photo["name"]; instead of putting "FOTOA" try putting the name property to see if it works

1

Come on,

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

  • So I tried to follow the above steps but also nothing different happened. :(

1

The mistake is that you try to use the $arquivo["FOTOA"] as if it were the file name. It is not. This index, nor does it exist. You are probably getting an error of this type:

Notice: Undefined index: FOTOA in ...

It’s right to wear it like this:

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

Beyond what was quoted by Alvaro Leandro that your form has to look like this:

<form  method="post" action="update-acidentes.php" enctype="multipart/form-data">
  • This "tmp_name" is the name of the html field?

  • @Marianaferreira no... This is the temporary location where the file is after you send it.

  • In php you can get some information from the file. If you give a print_r($_FILES["FOTOA"]) it will return you some things like... size - file size... tmp_name - temporary name... name - file name ... extension... errors...

Browser other questions tagged

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