How to display the saved image in the database in my html code

1

I have a mysql database created in phpmyadmin, already saved the path of the images, also in an image table with id and name (img), now I would like to know how to display these images in the respective places in my code html ... this is a part of the code where is the image that comes from a folder

            <img src="img/pat.png" class="img-responsive" width="300px" height="300px" align="#"></a>
            <div class="caption">
                <p> <h4><b> Restaurante Do Cardoso</b> </h4>
                <p align="justify"> />

In the place of that img / pat.png, I would like to put the path of the image that is saved in the database and display, but I am not able to ... already create the connection to the database and everything else

    
asked by anonymous 30.12.2017 / 13:44

1 answer

1

A simple solution is to create a .php file to manipulate the display of your images. You can create the following url to access your images: obterImagens.php?nome=nome_da_imagem

html code for requesting images

<img src="obterImagens.php?nome=imagem1" class="img-responsive" 
width="300px" height="300px" align="#">

<img src="obterImagens.php?nome=imagem2" class="img-responsive" 
width="300px" height="300px" align="#">

PHP code to return an image

Before the php code, I suppose you have a table in the database similar to this:

|nome_imagem|local_imagem|
Assuming images are saved to a directory in your file system, you can return them using the file_get_contents() function.

So, going back to php we can do this:

$nome_imagem = $_GET['nome'];
$conexao = mysqli_connect($conexao,'host', 'usuario', 'senha', 'nome_banco');
$consulta = mysqli_query('select * from imagens where nome_imagem = ' 
. "'" . $nome_imagem . "'");
//como o nome da imagem deve ser unico, apenas um registro deveria ser 
//retornado
$resultado = mysqli_fetch_assoc($consulta);

//como o campo local_imagem é o caminho absoluto ou relativo para 
//a imagem fica facil acessa-la agora.
$caminho_imagem = $resultado['local_imagem'];
//suponto que você salva todas as imagens no mesmo diretorio do script
//A varaivel $resultado['local_imagem'] poderia representar 
//apenas o nome da imagem, e você poderia concatenar os dois

 $mime = mime_content_type(__DIR__ . '/' . $caminho_imagem);
 $tamanho = filesize(__DIR__ . '/' . $caminho_imagem);

 header("Content-Type: ". $mime);
 header("Content-Length: " . $tamanho);

 //e por fim você manda para o navegador
 echo file_get_contents(__DIR__ . '/' . $caminho_imagem);

This response was adapted from a question available in the SOpt . NO SOen has a question (with answer) much closer than you want .

    
30.12.2017 / 18:27