PHP output image instead of string

Question

Im a complete novice when it comes to PHP so apologies in advance.

I'm trying to query my table and return all the data in a table, I have the below working only it returns the last column as the longtext string and I'd like to use that as an image source so it returns an image, does that make sense?

try {
 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $stmt = $conn->prepare("SELECT * FROM `o18-reg`");
 $stmt->execute();

 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

 foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
     echo $v;
 }
}

Show source
| php   | mysql   | pdo   2017-01-04 15:01 1 Answers

Answers ( 1 )

  1. 2017-01-04 15:01

    First of all, I d like to advise you should not place the image itself into database. You d better keep the Image URL or Absolute path in your file system into Database table.

    Also please make sure you set correct header info when to echo the image data. Without right header, it will be printed as string on client ends.

    So if the image is jpeg, you can add header code before you use echo to print the image like following: (Also do not forget to do base64_decode if you have encoded image data using base64)

    header("Content-type: image/jpeg");
    echo base64_decode($my_image);
    

    If it is png, then you can use following:

    header("Content-type: image/png");
    echo base64_decode($my_image);
    
◀ Go back