How to fetch image from database in PHP and display in table

fetch image from database in PHP

Fetching image from database in PHP and display in table is similar to fetch any data from database and show in HTML Table.

We generally store image at server and its path on database table.

We are considering an example of products to demonstrate the purpose.

Steps to fetch images and data from database is as below

  1. Create MySql Database table
  2. Upload image and store data in database table using PHP
  3. Fetch image and data from database using PHP

1 Create MySql Database Table

For this we have create a table product in ebhor database.

2 Upload image and store data in database table using PHP

Uploading images and data are not discussed here.

After uploading images and data our product table will look like this.

PHPMyAdmin Product Table
PHPMyAdmin Product Table

We are providing above data for copy and create your database

Here Image column contains the url where image is uploded.

You can learn more about PHP and MySql.

3 Fetch image and data from database using PHP

As you already seen images are stored in server file system and its path is stored in database.

To access data from database we can use either Procedural way using mysqli or PDO or object oriented way.

we will consider here procedural way to access data.

This is a simple PHP MySql select statment.

Steps to access mysql database with PHP

  1. Connect PHP with MySql using mysqli_connect("localhost", "root", "", "ebhor"); localhost means database is in same system, username is root, password is “” and ebhor is database name.
  2. check connection established or not if $connect==false means connection is not established.
  3. Create a query and pass it to mysqli_query(.....)
  4. It will return result in $result.
  5. if there are results then iterate each row and print in tabular format

By iterating mysqli_fetch_array($result) we are fetching row one by one and showing in tabular format.

To fetch image from url we use HTML tag <img src =""> as below


Photo by Pok Rie from Pexels
Image by ADMC from Pixabay
Photo by C D-X on Unsplash
Photo by ATC Comm Photo from Pexels

How to remove special characters from string in PHP

Characters other than alphabet [A-Za-z] and digits [0-9] are known as special characters like symbols & ^ % @.

Removing special characters from PHP string is very easy by using php library functions like

  1. preg_replace()
  2. str_replace()

Lets see them one by one

Using preg_replace() to remove special characters from string in PHP

PHP provides preg_replace() functions to remove special characters from string.

Lets see how to remove special characters from string in PHP using Examples.

Example: remove special characters from string in PHP.


Here preg_replace() is used for regular expression search and replace the string.

Syntax of preg_replace is

preg_replace($pattern, $replacement, $string)

$pattern: regular expression to find in string

$replacement: $pattern will be replaced by this

$string: The string on which we will find pattern and replace it.

Example: Remove special characters from string in PHP.


In above example

preg_replace('/[^A-Za-z0-9 ]/', '', $str);

Here $pattern is regular expression that specifies.

Consider A-Z and a-Z and 0-9 characters and a space (” “) in $str string.

Other then this replace any character with ”.

Example: Remove special characters except ! and . from string in PHP.


In above example two special characters are part of string ! and . we dont want to remove these two special characters for that we have included these two characters in pattern.

Using str_replace to remove special characters from PHP String

Syntax of str_replace is

str_replace($search, $replace, $string);
str_replace($search, $replace, $string, $count)

$search: The character or string you want to search on $string

$replace: $search will be replaced with $replace

$string: on given string we will apply search and replace

$count: Keep record of how many replacement performed.

Example: PHP program to remove special characters from string except dot


In above example we have created a character array of special characters and we want to replace with “”.

Result of str_replace() is stored in $str1.

Removing html elements from PHP string


In above example there are three html elements values showing as a part of string &bsp; &gt; &lt;

To remove this we used preg_replace("/&#?[a-z0-9]{2,8};/i","",$str);

This regular expression is taken from StackOverFlow

Removing comma and currency symbol from PHP String

Removing comma from currency


Removing comma (,) and currency symbol from PHP string currency


Using preg_replace() to remove currency symbol.


If you want to remove only currency symbol and dont want to remove comma (,) then you can use following regular expression with preg_replace().

preg_replace('/[^0-9,]/s', "", $str);

PHP String

String means set of characters or letters or combination in single or double quotes. Like ‘PHP Language’.

If you placed the number in the single quote or double quotes it’s also a string. Like ‘12345’.

Similarly, special characters symbol whatever if you write it in the single or double quote it’s become a string.

In PHP a single letter or character also a string. Like ‘A’

Creating and accessing String

In PHP language whatever you write in a code with a single or double quotation, it creates the string.

To declare a string always use the quotation, if you forget to mention quotes give you an error.

Syntax of String

Note: gettype() is a predefine PHP function which used to know the datatype of any variable. In this above example gettype() function return string.



PHP is a very good language and easy to learn And it supports many other languages like HTML, CSS, JAVASCRIPT and so on.

You can write a string with single quotes or double quotes both are equal. In above example $var and $var2 both hold string value.

Another Syntax of String:


In the first example, we want to print I’d buy myself, in this case, we never declare this string with the single quote because in the original value there has a single quote already.

Means in PHP language you never used the same type of quotes so start with the double quote.

In the second example, it returns Sum of 2 & 4 is $sum because we declare the string with single quote and variable also treated as a string in the single quote so it’s can’t return the value of $sum.

So never used the variable in a single quote but in the third example, we receive the value of $sum because double quote treats a variable like a variable so we can receive the value of any variable, not the variable name.

And in the fourth example, we used two type of quotation to declare a string. Because above example, we need to use nested quotes under the main quotes.

And in PHP language does not support the same type of quotes as a nested quote.

So in this type of case start with the single quote and used the double quote as a nested quote or start with double quotes and used the single quote as a nested quote.

If you don’t maintain these things PHP gives you an error.

Avoiding the single quote double quote complexity you also used escape sequences (\). PHP used \ symbols as an escape sequence.
Using this escape sequence you also rewrite those strings like this,

Syntax of String with \:

Another way to Create String (HereDoc):
In complicated cases, you need to create the large string.

And there you have to follow all rules of quotation or escape sequence to avoid error.

In PHP here has a new way to write the complex string with the simple manner.
3.1 Syntax of HereDoc:


This is another way of showing String Delimiters The value is Hello World
This is another way of showing String Delimiters The value is Hello World

<<< is a heredoc symbol. After <<< symbol an identifier is provided, then a new line.

Then you write your string and complete the string the same identifier again to close.

The closing identifier must be same as beginning in the first line and the identifier must follow the same case.

Identifier only starts with character or string or underscore (_) means it must contain only alphanumeric characters.

In above example, EOF and tutorial are the identifiers.

String functions in PHP- uses and examples

Now list some String functions in PHP to handle and manipulate string in PHP.

All functions explained are inbuilt PHP functions also known as predefined string functions in PHP.

These functions are defined during creation of PHP.

sterlen() Length of String

sterlen() function is used to get the entire length of the string. If there is space in between two words then it will count that space as well.



str_word_count() -Word Count

str_word_count() function will give you the exact number of words that a string have.



strrev() -String Reverse

strrev() function is used to reverse the entire string.


trim() -String Remove

Remove whitespace (or other characters) from the beginning and end of a string


Another example

ltrim() => Remove whitespace (or other characters) from the beginning of a string
rtrim() => Remove whitespace (or other characters) from the end of a string

ucfirst()- Convert first letter into uppercase

convert first letter into uppercase of any string

strtoupper() -to upper case

This function converts the string in upper case

strtolower() -Converts string to lowercase

convert whole string into lowercase

chr() -Return character from ASCII code

returns any character or letter and also special character from their equivalent ASCII Code

implode() -array to string

Implode function combine all array element with a string

String- convert to string


explode() -string to an array

Explode function split a string and return all value into an array.

Array- String to array conversion


strpos() -find the text position in string

strpos() function is used to find the particular text in a string.

If while searching in the string it founds the text, then it will give the position of that word in first search match or if the particular text is not found then it will return FALSE value.

Also first position of any character in string is 0 not 1.


str_replace() -Replace string

str_replace() function is used to replace some characters that are there in the strings.



PHP while loop syntax and example

While loop in PHP is also used for repeating statements in PHP.

PHP while loop check for condition if condition is true then code inside body of loop is get executed.

while – As long conditions is true, it loop back again and again through block of code.

while (condition is true) {
code to be executed;

Example: Write a program to use while loop in PHP.

The increment and decrement while loop count variable can used only inside loop.

Like here $a++ is used to increment the value of $a.

programmer has to take care of this otherwise while loop will be infinite.


The number is: 11
The number is: 12
The number is: 13

PHP File Upload Example

PHP File Upload is a very important topic in PHP.

Build any kind of websites or web application there has must be files.

So want know that how can upload files or retrieve those files and download it (if required).

You should have basic knowledge of Form Handling in PHP for working uploading a file.

Example: How to upload a file in PHP.

For Uploading a file:

  1. Create a HTML form with method POST and enctype="MULTIPART/FORM-DATA"
  2. Inside form create a input type file <input name="filedetails" type="FILE">
  3. Create a submit button to submit form to server.
  4. HTML Form action="" means file handling work is done by this file(upload.php)
  5. In PHP program check any file uploaded or not $_FILES['filedetails']['name']
  6. Get file and its detail on server.
  7. Save file to specified directory on server   copy($filesource, $destination);
  8. Show appropriate message to user.


PHP File Upload Example
Fig: PHP File Upload Example


Always use form method post for uploading the file, and enctype is mandatory, otherwise, the file doesn’t upload.

PHP File Upload need to set some options. By default uploaded file size is set 2M.

So sometimes file doesn’t upload if the file size is large than 2M.

That’s why set upload_max_filesize= 500M or any large value in the php.ini file (xampp/php/php.ini).

And also modify the post_max_size value in the php.ini file. By default post_max_size is 8M.

Sometimes for this reason also file doesn’t upload if the size is large then 8M instead of upload_max_size is greater than 8M.

So also set post_max_size=500M or any large value in the php.ini file (xampp/php/php.ini).

Any changes in the php.ini file need to restart XAMPP control panel. Stop apache and start again. Then the updated value will be reflected.

Read More

PHP for and foreach loop statement

It is used when one knows how many time one need to run the particular loop. It is also of two types:

1. PHP for loop statement

Loop back again and again through specified time duration.

PHP for loop syntax:

Example: PHP for loop example


The number is: 0
The number is: 1
The number is: 2
The number is: 3

2. PHP foreach loop statement

For each elements in the array it give result.
It is used to iterate all the elements over array.

PHP foreach loop syntax:

Example: PHP foreach loop example


PHP do while loop statement with syntax and example

If specified condition is true, loop through block of code once and then repeat again and again.

Syntax of PHP do while loop:



Do while loop is known as exit control loop because it check the condition at last(on exit).

Do while loop executes at least once when if condition is false.

PHP Switch Case Statement Syntax and Example

This statement is used if one needs to select one from multiple options.

PHP Switch Case Syntax:

  1. PHP switch case is used to select one among multiple options.
  2. inside switch we can use expression or  value
  3. inside switch there can be multiple case statement with different case value.
  4. case value must be constant.
  5. break is optional in php switch case
  6. Default is optional in php switch
  7. If any case does not match then default is executed.

Example: PHP Switch case statement

I booked Swift

PHP if else, else if Statements with examples

There are few conditional statements in PHP that is been used for putting different conditions. All the statements are as follows:

1. PHP if statement

It execute that code only if the situation is true otherwise not.
if statement Syntax:



2. PHP if else statement

If true then execute the result, but in case condition false then output will be other coded thing.

PHP if else Syntax:



3. PHP if…else if….else statement

Sometime first condition get false then to check or test another condition we use this statement.

PHP if…else if….else Syntax: