简体   繁体   中英

How to display through php an image stored in a folder considering that my image's link is stored in MySQL database

As good practice, I'm only storing my image's link in my database, the questios are:

How should I store my image's link? (let's say it's on c:)

c://image.jpg ?

Which peace of PHP code should I use to display that image? I'm only displaying the path, what should I do to display the image?

Can I use this:

$query = "SELECT ImageURL from WhateverTable";

$result = mysql_query($query) or die(mysql_error());

$Image = mysql_fetch_row($result);

echo "<img src='$Image[0]' alt='This is an image'>";

Thank you all lads

You only want to store the relative path, not the absolute path, as linking to something like

 <img src="/var/www/vhosts/website.com/images/file.jpg"> 

would return a 404 on any real website. store your files in the database via a relative path (/images/file.jpg) or by only the filename if they are all in the same directory.

alternatively, you can learn MongoDB and it allows you to actually store files in the database itself.

  1. I would strongly suggest that you use PDO instead.
  2. Use relative URLs to your image folder in case you need to move them one day.

Here is an example.

// relative to your public webroot
$publicImageUrl = '/images/in/here';

// Pull up some record, maybe of a product 
$select = 'SELECT imageFilename FROM products WHERE id = 2332';
$results = mysql_query($select);
if(!$results) {
    // issue with query. deal with it here
} else {
    if( mysql_num_rows($result) ) {
        // record not found. deal with it here
    }

    $row = mysql_fetch_array($result);

    $imageSrc = $publicImageUrl  . '/' . $row['imageFilename'];
}

And then your HTML would be as follows

<img src="<?php echo $imageSrc; ?>" />
  1. use PDO for php <-> mysql connection

  2. post mysql query output

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