How to save an image of a form to the bank

Asked

Viewed 1,069 times

1

In my form, the user puts the information of your request and an image for reference, however, this image is not being saved along with the record.

The form:

<!DOCTYPE html>
<html lang="utf-8">
<head>
    <meta charset="UTF-8">
    <title>Documento</title>
</head>
<body>
    <?php
        if(isset($_FILES)){
            $dir = "../img/";
            $image = $_FILES['image']['name'];
            if(move_uploaded_file($_FILES['image']['tmp_name'], $dir.$image)){

                $image = $_FILES['image'];

                $strcon = mysqli_connect('localhost','root','', 'db_formacao') or die('Erro ao conectar ao banco de dados');
                $sql = "INSERT INTO imagens SET image = '$image'" 
                mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
                mysqli_close($strcon);

                echo '<script type="text/javascript">
                        alert("Salvo com Sucesso !");
                        window.history.go(-1);
                    </script>';
                ?>
            }
        }
    ?>
    <form id="formulario" method="post" enctype="multipart/form-data" action="">
        Selecione uma imagem:
        <input name="image" type="file"/>
        <br/>
        <button type="submit">Salvar</button>
    </form>
</body>
</html>

It’s giving the error 500, the page is not working.

This is the first time I’ve tried to save an image, so if something is absurdly wrong, point me. :)

  • How’s the tipo field in your database ?

  • So it’s really sweeping. I looked for a more suitable option but I couldn’t find,

  • The correct one would be "blob". Take a look here: http://www.devmedia.com.br/storage-imagens-no-mysql/32104

  • @Raonibz The right thing would be blob? are sure?

  • 1

    Your line of SQL is wrong, change to that $sql = "INSERT INTO imagens SET campo ='$image' and to get the name of the image, you need to do so $image = $_FILES['imagem']['name']

  • @Rafaelaugusto as far as I know, yes, the blob ! Which would be ?

  • @Rafaelaugusto INSERT INTO imagens SET campo ='$image' ???

  • 1

    @Raonibz The best practice is to store only the file name in the database and the image in the server directory.

  • @Raonibz What is your doubt regarding my answer in the above comment?

  • @Rafaelaugusto for sure ! I have even ready example of this, but the question was not that.

  • Why not values, if it is the most common ? INSERT INTO imagens (imagem) VALUES ('$image')

  • 1

    It’s not about being ordinary or not, you don’t have sintaxe wrong, one is the SQL and another of Mysql, I gave an example of the way I use it, which doesn’t stop her from using it with values, and still discover that it is possible with SET

Show 8 more comments

1 answer

1

To manipulate a file, one must use the

$_FILES (http://php.net/manual/en/reserved.variables.files.php)

Saving images in the bank is by far not a good practice ! rs

As requested by the chat, a complete example of uploading the file to a directory and the file data in the database: (take an image named "loading.gif" and leave it in the root folder, it will display it while the form sends)

*** Create an "attachments" folder in the root folder.

index php.

<html>
<head>  
    <link type="text/css" rel="stylesheet" href="../assets/css/materialize.min.css"  media="screen,projection"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#formulario").submit(function() {
                $('#formulario').hide();
                $('.imagens').hide();
                $('#gif').show();
                //return true;
            });
        });
    </script>
</head>
<body>

    <img src="loading.gif" id="gif" height="auto" width="200" hidden>

    <form id="formulario" method="post" enctype="multipart/form-data" action="_envio.php">
        Selecione uma imagem: 
        <input name="arquivoX" type="file"/>
        <br/>
        <button type="submit">Salvar</button>
    </form>

    <?
    date_default_timezone_set('America/Sao_Paulo');

    $srv    = "enderecoDoBanco";
    $user   = "usuarioDoBanco";
    $pass   = "senhaDoBanco";
    $db     = "nomeDoBanco";

    $db = new mysqli($srv, $user, $pass, $db);

    $sql = "SELECT * FROM anexos";
    $res = $db -> query($sql);

    while ($i = $res -> fetch_assoc()) {

        $a[] = $i;

        //echo "<pre>";
        //print_r($i);
        //echo $i['dir'].$i['arq'];
        ?>
        <img class="imagens" src="<?echo 'anexos\\'.$i['arq']?>" height="60" width="60"/>
        <?
    }
    ?>

</body>
</html>

_php.

<?php

date_default_timezone_set('America/Sao_Paulo');

$srv    = "enderecoDoBanco";
$user   = "usuarioDoBanco";
$pass   = "senhaDoBanco";
$db     = "nomeDoBanco";

$db = new mysqli($srv, $user, $pass, $db);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
} else {
    echo '<div style="background-color:green;color:white"><b>OK :: CONEXAO BD</b></div><hr>';
}

echo '<pre>';
print_r($_FILES);
print "</pre>";

$uploaddir = 'F:\Xampp\htdocs\_commands\files\anexos\\';
$uploadfile = time() . '-' . basename($_FILES['arquivoX']['name']);

if (move_uploaded_file($_FILES['arquivoX']['tmp_name'], $uploaddir.$uploadfile)) {

    // Gera endereço da pasta para o mysql
    $dir = str_replace('\\', '\\\\', $uploaddir);

    // ******* TRATAR NOME (acentos, etc)

    $arq = $uploadfile;
    $extpat = pathinfo($_FILES['arquivoX']['name']);
    $ext = $extpat['extension'];

    echo '<div style="background-color:green;color:white">OK :: Arquivo válido e enviado com sucesso.<br></div>';
    $db -> query("INSERT INTO anexos (`dir`,`arq`,`ext`) VALUES ('$dir','$arq','$ext')");

} else {

    echo '<div style="background-color:orange;color:white">WARNING :: Possível ataque de upload de arquivo!<br></div>';
}

if ($db -> close()) {
    echo '<div style="background-color:blue;color:white"><b>OK :: CONEXAO BD CLOSE</b></div><hr>';
} else {
    echo '<div style="background-color:orange;color:white"><b>WARNING :: CONEXAO DB CLOSE</b></div><hr>';
}

sleep(3);

header('Location: index.php');

?>
  • This upload in _send.php is equivalent to my address of the images folder, right?

  • What "arquivoX" is this? What "Extension" is this?

  • yes ! uploaddir is the directory that will be sent to the image (take care, take a small image for testing, because php limits size)

  • The name "arquivoX" is the input in the index <input name="arquivoX" type="file"/>

  • And this "Extension" is to extract the file extension. So I know the type of each. But this was a TEST to test these variables all.

  • I made some changes and is giving error 404. I will update the question.

  • You’re simulating this where ? Your scenario accepts "short tag" = <? instead of <?php

Show 2 more comments

Browser other questions tagged

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