Upload mysql image

Asked

Viewed 161 times

1

I am in need of a help to develop a code to store images in the database, so far I have not achieved anything... I don’t know if it is better to store the file in a directory and only the name in the bd, and mainly how to 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 pull the images by id...

  • 1

    what you’ve tried friend?

  • I edited the question, see if you understand...

  • Read this - http://answall.com/questions/42886/salvar-no-banco-de-dados-conte%C3%Bado-bin%C3%A1rio-de-uma-imagem

  • So, I don’t know if it would look better on a directory or on the db itself...

  • Read the answers to this link, in attention to the last that has some good references on the use, and then maybe you can know which to use.

1 answer

0


Bruno, the most common practice is to store the image in a directory and only store the path in BD, otherwise you will need to research more deeply on data type blob. The way you’re doing it, you’ll get it this way:

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

register.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.";
}
  • Thank you very much Thyago, now I understand very well :D

  • @Brunoferreira we are there, arrange... =)

Browser other questions tagged

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