Insert imagem.jpg in the database

2

Good morning! Home I want to insert an image in the database in .jpg format, but when it is inserted it appears like this in the database: ???? JFIF
Here is my code related to the image:

<form action="" method="POST" enctype="multipart/form-data">
   <input type="file" name="imagem" placeholder="Insira a imagem do produto" required/>
</form>
<?php
    $imagem_produto=addslashes(file_get_contents($_FILES['imagem']['tmp_name']));
    $inserir_produto=mysqli_query($link,"INSERT INTO produtos (imagem) VALUES('{$imagem_produto}')");
?>

What I wanted was for the database to display the name and the extension of the image, for example "imagen.jpg", just that!

    
asked by anonymous 08.06.2018 / 11:22

2 answers

3

If you just want the name, why not use it?

$nome_img = $_FILES['imagem']['name'];
if(move_uploaded_file($_FILES['imagem']['tmp_name'], "images/".$nome_img)){
   $inserir=mysqli_query($db, "INSERT INTO coluna(nome) VALUES ('$nome_img')");
}else{
   echo "Erro!";
}

This will insert the image into the database.

I suppose you have a code for uploading but I leave it here anyway.

I also stress that I usually use varchar(255) in the database.

    
08.06.2018 / 12:04
1

The field of the table where your image is going to have to be blob or mediumblob depending on the size you need! Then just show the row on the side you need and it will appear!

Code to insert image

Make a button and make it submit with the name="submit"

if(isset($_POST['submit']))
{


 $name = $_FILES['imagem']['name'];
 $target_file = basename($_FILES["imagem"]["name"]);

 // Select file type
 $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

 // Se quiseres só jpg deixa só jpg
  $extensions_arr = array("jpg","jpeg","png","gif");

 // Check extension
 if( in_array($imageFileType,$extensions_arr) ){

 // Convert to base64 
 $image_base64 = 
 base64_encode(file_get_contents($_FILES['imagem'] 
['tmp_name']) );
 $image = 'data:image/'.$imageFileType.';base64,'.$image_base64;


$query="INSERT INTO produtos(imagem) VALUES ('".$image."')";
$query_run = mysqli_query($conn,$query);
    
08.06.2018 / 11:35