Uploading mysql image

1

I need help to develop a code to store images in the database, so far I have not achieved anything ... I do not know if it is better to store the file in a directory and only the name in the bd, and mainly how do this ...

<form method="post" enctype="multipart/form-data" action="cadastrar.php">
<table>
<tr><td>imagem:</td><td><input type="file" size="60" name="arq" value=""></td></tr>
</table>
</form>
$arq_name = $_FILES['arq']['name']; //nome do arquivo
$arq_size = $_FILES['arq']['size']; //tamanho do arquivo
$arq_tmp = $_FILES['arq']['tmp_name']; //nome temporário do arquivo

//grava no DB
mysql_query("INSERT INTO users (foto) VALUES ('$arq_name')");
//grava a img no diretório
move_uploaded_file($arq_tmp, "imagens/".$arq_name);

Now I just have to be able to get the images by id ...

    
asked by anonymous 24.10.2015 / 04:56

1 answer

0

Bruno, the most common practice is storing the directory image and storing only the path in BD, otherwise you will need to drill down to blob-type data. In the way you are doing, you will do this:

<form method="post" enctype="multipart/form-data" action="cadastrar.php">
<table>
<tr><td>imagem:</td><td><input type="file" size="60" name="arq" value=""></td></tr>
<tr><td></td><td><input type="submit" size="60" name="enviar" value="Upload"></td></tr>
</table>
</form>

cadastrar.php

if($_POST["enviar"]) {

    $tempname = $_FILES["arq"]["tmp_name"];
    $new_name = uniqid(); // Novo nome aleatório do arquivo
    $extension = strtolower(pathinfo($_FILES["arq"]["name"], PATHINFO_EXTENSION)); // Pega extensão de arquivo e converte em caracteres minúsculos.      
    $folder = "imagens"; // Pasta onde será armazenada a imagem.

    if(move_uploaded_file($tempname, $folder."/".$new_name.".".$extension)) { // Move arquivo para a pasta em questão e com o novo nome.
        // Grava no DB
        mysql_query("INSERT INTO users (foto) VALUES ('$new_name.".".$extension')");
        echo "Arquivo enviado com sucesso.";
    } else echo "Erro ao enviar arquivo.";
}
    
24.10.2015 / 09:57