For ordinary website images, keep the image file in a controlled upload directory and store only its generated file name or relative path in MySQL. Escape both text and the generated HTML attribute values when displaying records.
<?php$result=$connection->query('SELECT id, name, image_file FROM image_gallery ORDER BY id DESC');
while ($row=$result->fetch_assoc()) {
$name=htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');
$file=rawurlencode(basename($row['image_file']));
echo'<p>'.$name.'</p>';
echo'<img src="uploads/'.$file.'" alt="'.$name.'" class="img-fluid">';
}
?>
If an application intentionally stores binary image data in a database, use a BLOB workflow designed for that purpose rather than mixing binary data with a file-path example.
We will not store the image in MySQL table ( plus2_db_images) but store the image name in table record. While displaying the image we will show other details of the record like ID, Price and Name of the image. You can download the script with all images at the end of this tutorial .
Connecting database and executing Query
To manage data we have to connect to MySQL database and execute query to get our date. Here there are two ways to use PHP drivers to connect to MySQL and execute the functions for getting records.
Images are stored inside image directory. The name of the image is stored in the record. We are not storing the path of the image in our record as we can change the path in our PHP script easily than using SQL to update the records if any changes in path is required.
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.