Polymorphism in PHP with Example

Polymorphism in PHP is one of the important concept in OOPs.

Polymorphism is a Greek word. Polymorphism is created by two different words poly (means many) and morph (means forms).

It is another functionality of OOPS. In programming language two types of Polymorphism are there.

  1. Function overriding (Run time Polymorphism)
  2. Function Overloading(Compile time Polymorphism)

Function Overriding in PHP

Overriding is happened only in child class.

If parent class declares a function and child class wants to override parent class function then function overriding means run time polymorphism happened.

Polymorphism example in PHP

Here are are taking a simple example.

Created a class parentclass it has a method name().

created another class childclass it inherits the feature of parentclass.

child class has also the same method name().

Defining the same method in child is know as method overriding.

Output

 
Calling show method of Shape
Shape is no defined
Calling show method of Circle
Showing a Circle
Calling show method of Rectangle
Showing a Rectangle
Calling show method of Square
Showing a Square
Calling show method of Triangle
Showing a Triangle

Polymorphism example to call different methods in PHP

Here we have taken example of Shapes.

Shape is a base class with a method show().

Child classes of Shape are Circle, Rectangle, Square and Triangle.

all have a over ridden method show().

Polymorphism Example in PHP

Output

 
Calling show method of Shape
Shape is no defined
Calling show method of Circle
Showing a Circle
Calling show method of Rectangle
Showing a Rectangle
Calling show method of Square
Showing a Square
Calling show method of Triangle
Showing a Triangle

Read More

  1. PHP Inheritance

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

Read More

  1. PHP MySQL CRUD Tutorial with MySqli and PHPMyAdmin
  2. How to Export and Import MySql Database using phpMyAdmin
  3. PDO in PHP

Resources:

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.

Output

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.

Output

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.

Output

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

Output

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

Output

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

Output

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

Output

Using preg_replace() to remove currency symbol.

Output

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.

Example

Output

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

Explanation
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:

Explanation

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:

Output

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

Explanation
<<< 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.

Result:

Result:

str_word_count() -Word Count


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

Result:

Result:

strrev() -String Reverse


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

Result:

trim() -String Remove


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

Output

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

Output

explode() -string to an array

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

Array- String to array conversion

Output

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.

Result:

str_replace() -Replace string

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

Example:

Result

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.

Syntax:
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.

Result:

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

PHP Form Handling with Examples

PHP Form method is used to sending data from browser to server.

Two types of methods are there GET and POST.

$_GET and $_POST are used to receive value from the form method.

$_GET and $_POST are the global variables so declare it with uppercase otherwise this will not work.

Syntax of GET Method in PHP:

Output:
Bill

Syntax of POST Method in PHP:

Output:
Bill

Note: by default form method is get.

If any user does not declare method attribute in the form tag then value send by getting method automatically.

If any users declare form method attribute value post and receive value in the server using $_GET variable then it does not work same as vice versa.

Get and Post method both are same and used for the same purpose but there has some difference.

Html/Text Response from PHP

Sending any kind of data from the form all go as a string type.

Program: PHP Program to submit user details in PHP form and show in PHP HTML table format.

Output

User Form in php
User Form
User Form in PHP
User Response

Send JSON Response from PHP Form


JSON is another way to use for exchange data format between web client and server.

Enabling HTML forms to submit JSON directly simplifies implementation as it enables backend services to operate by accepting a single input format that is what’s more able to encode richer structure than other form encodings (where the structure has traditional had to be emulated).

Form’s type attribute value set application/ json to transmit JSON data from the form.

Example: Form submit in php to send user details and get PHP JSON response.

Output

PHP Form to enter user details
PHP JSON OUTPUT

Explanation:
By default input type is text.

Value send from the form by method and json_encode is a function which exchanges PHP server data into JSON format.

Example: How to Upload an Image in PHP

Output:

File Upload Example in PHP
Uploaded file detail in PHP

Explanation:
Upload any kind of file through form need set enctype attribute value with multipart/form-data. It means multi-type file can upload from Form.


Next always use post method in form because get method only sends 1kb data.


Next file value receives always in the server via $_FILES[] global array whatever form method in form, Which has 5 parameters name size type tmp_name and error.


Name index return name value of the uploaded file.
Size index returns size value of the uploaded file in bytes.


Type index return uploaded file type value like image/jpg for jpg extension file, application/pdf for pdf file, application/docx for document file, plain/text for text file etc.

Tmp_name index returns the uploaded file location. In server, there has a tmp folder initially where all the uploaded files are stored temporarily.


Error index return by default 0 otherwise if the size or any other index value return any error then error index return 1 or 2

Want Upload pdf file then only change the condition of above example

Example: How to Download a File in PHP


Explanation:
Provide file name to download,set its content type.

on calling url it will get downloaded.

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.

upload.php

PHP File Upload Example
Fig: PHP File Upload Example

Showfile.php

Note:
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

Result:

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

Result:
swift
alto
toyoto
I10

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:

Example:

Result:

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.