0

I'm new to php and mysql. I created databse in mysql, and I would also like to display my image from the database to my php site, but I only get a weird code (something like this: ����JFIF,,��), everything else works as it should. This is my code:

<?php
$mysqli = new mysqli('localhost','root','','bas');
$result = $mysqli->query("SELECT * FROM bas1");
if($result->num_rows !=0)
{ while($rows = $result->fetch_assoc()
  {$name=$rows['name'];
   $price=$rows['price'];
   $rate=$rows['rate'];
   $image=$rows['image'];
   echo "<tr>";
   echo "<td>$name</td><td>$price</td><td>$rate</td><td>$image</td>";
   echo "</tr>";}
 } else { 
echo "<tr>";
echo "<td>";
echo "no rusults";
echo "<td>";
echo "</tr>";}
?>

The image in databse is set to longblob. I would be very thankful if someone could help me

  • Very bad idea to store image in database :) The image would have been encoded in some format. Have a look at this link - https://stackoverflow.com/questions/16262098/displaying-a-base64-images-from-a-database-via-php – Sudipta Mondal Jun 07 '18 at 06:21
  • Please check there is an unwanted space in your image (img) tag. – Arsalan Akhtar Jun 07 '18 at 06:21
  • @sudiptamondal storing images in databases is a perfectly good idea. However, for larger files, a file server may do the job better. – Strawberry Jun 07 '18 at 07:28
  • @Strawberry encoding/decoding images again from database. Additional step, which I would want to avoid. Also for a very large image, if you show it directly in php using the data attribute, it makes the page slower. So not very good from a web dev point of view – Sudipta Mondal Jun 07 '18 at 08:45
  • @SudiptaMondal You may want to avoid it. It doesn't make it a bad idea. – Strawberry Jun 07 '18 at 08:46
  • @Strawberry you may want to read the whole of the comment – Sudipta Mondal Jun 07 '18 at 08:47
  • @SudiptaMondal Likewise! – Strawberry Jun 07 '18 at 08:48

2 Answers2

0

try this

use img tag and encode the image

echo '<img src="data:image/jpeg;base64,\'.base64_encode( $image ).\'"/>';
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
-1

I recommend you to not to store an image in the database you should store image somewhere in server directory and save the path of that image in the database. and display image like this

<img src="<?php echo $image?>">

and your image data type in your database should be text.

Noman
  • 1
  • 3
  • you explain bit more plss. – Bhargav Chudasama Jun 07 '18 at 06:42
  • Yes, how do you mean store somewhere in server directory? – Unknown Jun 07 '18 at 06:45
  • 1)change your datatype from blob to text in databse, 2) then store the name of image in database e.g(imgage.png), 3) store the image in same directory where your php file is residing 4) now fetch the name of image from database ,5)then set the image source name to this name like this, – Noman Jun 07 '18 at 06:50
  • Thanks man, will try it :) But does it matter if its varchar or char? – Unknown Jun 07 '18 at 07:18