简体   繁体   中英

Displaying an image in php using mysql

I'm trying to display an image along with other information from the database.

PHP

  <?php
               mysql_connect("localhost","111","222") or die("Could not connect to localhost");
               mysql_select_db("movies") or die( "Could not connect to database");

               $result = mysql_query("SELECT * FROM allmovies");
               if ($result == false )  die(mysql_error()); 
               while($row = mysql_fetch_array($result))
               {
                    echo "<img src=' . $row['image'] . '>";
               ?>

Like:

Title: Blah
Price: Blah
Image: <img src=rarara">

All from MySQL in one page?

  1. Don't store image data in a database, they are generally not suited to this and incurs extra overhead on your MySQL connections returning the data. You should be storing the path to the image file , and serving that.
  2. If you insist on doing it you you should only be returning one image at a time with the proper header based on the image type using something like the following:

     $imagedata = data_from_mysql(); header('Content-Length: ' . sizeof($imagedata) ); header('Content-Type: image/png'); echo $imagedata; exit; 
  3. If you really want to make your page source bloated, slow, unmanageable, and nigh-uncacheable:

     while( $imagedata = data_from_mysql() ) { echo "<img src='data:image/png;base64," . base64_encode($imagedata) . "'>"; } 

I cannot stress enough how these are terrible ideas that you should not use , but if you cannot listen to reason you can at least do bad things the right way.

You could use imagecreatefromstring()

$im = imagecreatefromstring($row['image']);
if ($im !== false) {
    ob_start();
    imagejpeg($im);
    $data = ob_get_contents();
    ob_end_clean();
    echo '<img src="data:image/jpg;base64,' .  base64_encode($data)  . '" />';
}

Just my opinion, but it might be slightly more sane to save the images to the file server and then store a reference to the path instead of the whole image as a blob?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM