Home » Posts tagged 'php'

Tag Archives: php

Polymorphism

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)-  PHP function overloading is not supported yet.

Function Overriding:

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.

Example

Please follow and like us:
error

PHP Abstract Class

Abstract keyword is another new functionality in OOPS.

When a class declare by Abstract keyword this class cannot be instantiate. Means if user declares a class as an Abstract class he or she cannot create object of that class.

Abstract class is only use for inheriting another class. Main purpose of creating abstract class is to protected or restricted from direct object creation.

Example:

Output:

Please follow and like us:
error

PHP Final Class

In PHP 5 a new mechanism added in OOPS which is Final Keyword.

If a class declares by final keyword then the class never extended. Child class can’t be created of any Final class.

It is restrict the overriding a method.

Only class and function may be declared as Final but no variable or properties cannot declare as Final.

Example

Output:

Please follow and like us:
error

PHP Inheritance

Inheritance is a wonderful feature of OOPS. It is solved the duplication of code.

Code duplication happened when user uses same code multiple times. Using Inheritance declare the logic in one class and extends it whenever needs to use it. And also add new functionality with old one.

In Inheritance, there have parent or base class and a child or derived class. Write logic in parent class onetime and reuse it many times in child class.

Child class has the power to access all or a few methods and variables of the parent class. Child class has also own member variables or functions.

Child class has the power to access all or few methods and variables of the parent class. Child class has also own member variables or functions.

How to extend Parent or Base Class

Output

Parent Class:  A class which is inherited from another class that is called parent or base or superclass.

Child Class: A class which is inherits from another class that is called child or sub or derived class.

In this above example, Animal is a parent or base class and Dog is a Child class.

Dog class can access Animal class member variable and function for Inheritance. Extends keyword helps to create a child class.

Whenever wants to inherit parent class then need to use extends keyword to create child class.

Child class cannot access all properties of parent class. In PHP there are 3 types of Access Specifiers.

Public: By default all class member variable and functions are public member.

All public members of parent class can, by child class and also out of the uses. Public member define by Public Keyword.

Private: Private member defines by Private Keyword. Only Parent class can be accessed Private property.

Private property cannot be access in child class and out of the class.

Protected: Protected Member defines by Protected Keyword. Protected Members are only access into Parent Class and its child class.

Protected property cannot access out of the class.

Example

Five Types of Inheritance in Programming Language:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

But in PHP only Single and Multi-level inheritance supported.

  1. Single Inheritance: There only one base class and one child class. Child class only derived from one base class.

Example:

  1. Multi-Level Inheritance: There one base class derived one child class and that child class derived another child class and so on.

Example

Please follow and like us:
error

PHP Constructor and Destructor

If the user wants to access any member function of a class then he or she must create the object first then call the member function by this object.

The constructor is a method or way which automatically called when an object the for a class.

No need to call it by an object. Simply constructor is a function which called when object creates of class.

Constructor declares by two ways.

  1. Define function name same as class name. (This is old way to declare constructor. It is use in PHP 5.3.3 version)
  2. Define function by __construct keyword.

Only one constructor creates in one class. It is used to run an operation which needs to run at first of any other operation.

Like Database Connection. The constructor

Example:

Output:

Explanation:

In above example $dell is an object of Computer class when its created constructor automatically called and CPU, RAM and Hard disk value passed by parameter.

Then when called describe() function its return the whole value

Destructor

the is also a method or way in OOPS which is opposite of Constructor.

Destructor also called automatically when object an of any class but it’s run when The constructor creates.

It the for free up memory. Using this after complete a task unset all variable and re The constructor it in next program.

Destructor defines by __destruct keyword. an is also a function which automatically called when object The constructor.

Example:

Output

Please follow and like us:
error

PHP Class and Objects

Class and objects is a programming template to write a program in a block.

It is helps to developer write complex program in simple way, reuse a program in multiple applications and create a structural program.

A class has two member one Variables and two Functions. A class is a program structure where developer defines application logic.

Object is a way which use to access class. Create an object developer access their application logic which defines in a class anywhere in a project.

Class and Object is a very useful and easy way to create a complicated application in a simple way.

Creating Class:    

Explanation:

Create a class with “class” keyword then define a class name. The name must start with string or underscore (_).

PHP is a case sensitive language so class name also case sensitive. Means Pen is write word to access this class. start PEN,  pEn, The name not the same.

Between { } define whole logic or code. Variable must be declared with var keyword or public keyword and all logic operation must be defined in function.

Creating Object

Explanation:

new keyword create object of a class. Object has authority to access the class variable and function out of the class.

In this example $obj is an object of Pen class, $obj can access $name, $price or can call the describe() function out of the class.

Object never creates within class.

Accessing Members and Functions

Output:

Explain:

Accessing class member variable and function by object. “->” this is accessing symbol.

$this variable is use to access class member variable in to the class member function. $this is object pointer, with reference an instance of class.

Please follow and like us:
error

PDO in PHP

What is PDO?

Other than procedural methods like MySQLi, PHP also provides an object oriented approach to deal with databases. This framework is widely known as PDO: PHP Data Objects.

Advantages of PDO

  • PDO is applicable on 12 different databases whereas MySQLi is not, which makes PDO more flexible than typical procedural approach.
  • PDO also provides an exception class for handling problems during database query execution. The exception-prone code must be written in the try block. When an exception is thrown within the try{ } block, execution stops at that line and jumps directly to the first catch(){ } block.
  • PDO provides a set of methods on the PDO object for performing queries, which introduces reusability of code.
  • It’s useful for developing software that may deploy in environments containing different databases available without having explicit support to each database, also for using a database connection with little or no knowledge of the database.
  • mysqli doesn’t allow you to handle exception. The function die(); will just stop executing the script suddenly and then show the error to the screen to the user which is NOT desirable & allowing hackers to discover your schema.

PDO provides three error handling modes:

  1. PDO::ERRMODE_SILENT acts like mysqli where you have to check each result and then look at $db->getMessage(); to get the error details.
  2. PDO::ERRMODE_WARNING throws PHP Warnings on the output screen.
  3. PDO::ERRMODE_EXCEPTION throws PDOException. This is the best mode use. It acts much like or die(mysql_error()); when it isn’t caught, but unlike die() the PDOException can be caught and handled if you want to do so.

Limitation of PDO

The Limitation is that you lose direct control of your queries, which can make complex queries difficult to write or move a lot of operations off the database and into PHP, requiring larger results thereby reducing code and database performance.

PDO Set Up

For installation procedure, visit: http://php.net/manual/en/pdo.installation.php

Examples

Database Connection Establishment using PDO

Here is an example using PDO:

Run Query Without variables

For simple queries without PHP variable parameters, use the following PDO code:

Just change query for the simple DELETE, and INSERT statements within the above written code.

Run Query With PHP Variables

For statements that take PHP variable parameters, MySQLi uses a long tiring process to perform the task whereas PDO offers you an easier process using method calling. The example for SELECT statement is as follows:

Here we have performed three steps as follows:

  • Prepare: A valid query template is created and sent to the database where some values are unspecified (labelled as “?”).
  • Then the database parses, compiles, performs query optimization on the query template, and also stores the query result without executing it.
  • Execute: Later on, the application binds the values to the parameters, and the database executes the statement in lesser time using execute. The application may execute the prepared query as many times as the user wants with different values as per the requirements. It is a safer solution than concatenating strings together using MySQLi approach.

N.B.: While binding parameters, never put quotes around the ‘?’ placeholders. It will cause SQL syntax errors because quotes aren’t needed to be known while preparing the query.

Please follow and like us:
error

PHP Regular Expressions

What is Regex?

Regular expressions (regex) are a sequence of specific characters itself. Generally the regex consists of arithmatic operators & alphanumeric characters to construct specific patterns.

These patterns are widely used for customized validation as per user requirement.

Functions

PHP provides us three functions to deal with regular expressions:

preg_match: The function is used to check pattern match on a string. It returns true when match is found and false if no match is found.

preg_split: The function is used for pattern matching on a string and then splits the results into a numeric array

preg_replace: The function is used to identify a pattern match on a string and replace the matched portion with the specified text.

Below is the general syntax for a regex function such as preg_match, preg_split or preg_replace.

Syntax–

Here,

func_Ebhor” is one of the three functions already described above.

The forward slashes denote the starting and ending of the specific regular expression

Ebhor_regex” is the particular pattern that needs to be matched

Ebhor_txt” is the text string needs to be matched with Ebhor_regex.

Meta characters

The meta characters help us to perform complex pattern matches such as test the validation of an email, telephone, unique username etc. Here is some commonly used meta characters:

Meta CharacterDescription/Example
.Dot matches any single character except a new line character././ matches anything having single character in it
^It matches the beginning of a string./^eb/ matches any string that begins with eb
$Dollar sign matches pattern the end of the string/in$/ matches robin, coffin etc.
*Star matches zero (0) or more characters in the given string./con*/ matches continuous, control, connection etc.
+Plus requires preceding character(s) to appear at least once./ebh+or/ matches ebhor
\Backslash is helpful to escape meta characters./ebhor+\.com/ considers the dot as a literal value during pattern match
[…]Character class/[abc]/ matches abc
a-zIt matches lower case letters./a-z/ matches cool, happy etc.
A-ZIt matches upper case letters like EBHOR, PHP, REGEX etc.
0-9It simply matches any number between 0 and 9./0-3/ matches 0,1,2,3 etc.

Predefined Character Ranges

There are some predefined character ranges, known as character classes, are available in PHP for easier coding.

Character classes contain a collection of specific characters within a range. Some of the most popular character classes are given below:

Sr.NoExpression & Description
1[[:alpha:]] It matches with any string containing alphabetic characters between aA and zZ.
2[[:digit:]] It matches any string containing digits within the range 0 to 9.
3[[:alnum:]] It matches a string containing alphanumeric characters aA-zZ and also 0-9.
4[[:space:]]It matches with any string containing blank space.

Examples

Here is an example of PHP validation using regular expressions:

Please follow and like us:
error

PHP and MySQL

PHP and MySQL connectivity is a very important topic while learning PHP here step by step PHP and MySQL connectivity and create update delete and read operations are discussed using mysqli and using PHP Data Objects(PDO) are discussed. To create database and tables PHPMyAdmin are used.

MYSQL is a freely available open source Relational Database management System (RDBMS)**  that uses Structure Query Language (SQL).

SQL is the most popular language to accessing, adding and managing content in a database. It is popular because its fast process, reliable, ease and flexible of use.

PHP can connect to MYSQL and manipulate database. It is used on the server. Create any PHP application need MYSQL database to managing data. MYSQL is an important part of most of all PHP application like WordPress, Joomla, Magento and Drupal. MYSQL is a one kind of database system for web application with huge size of storage space (like Facebook, Twitter and Wikipedia)

MYSQL are stored data in tables. A table is a collection of related data, one kind of array. 

But PHP can store data and managing data except MYSQL by using another database like ODBC(Open Database Connectivity).

Note: **RDBMS is a collection of data, stored and accessed virtually. RDBMS is used for the definition, querying, creation, update and administration of databases. It is a software application to interact with user, other application means programming language (PHP, JAVA, .NET, Python etc.) and also database itself analyze data.

Create Database on Server

In the XAMPP OR WAMPP server PHPMYADMIN is present for MYSQL. Open XAMPP or WAMPP control panel start Apache and Mysql. Then enter localhost/phpmyadmin on the browser url. Open PHPMYADMIN section which is the main MYSQL database. Here database, table can create and also data stored and manage.

Click on the Database option then open a text box to create new database with database name.

Enter database name in the open textbox and click the Create button. Remember one thing never used space between two words of database name only used – (dash) or _ (underscore) and MSQL is case sensitive so database name and table name field name are use same as it is.

If user create database with same name (previous any other existing database name) then new database is not create. Always set database name similar with application (like create school management system then create database for this application with school_management name).

When a database is created successfully then this database shown in the left side list with alphabetical order. Click the database then open particular those database table list or if there has no table then show below image.

In MYSQL there has no limit to create database.

PhpMyAdmin creating table

Create Table in a database MYSQL

Create table in a particular database is very simple like create new database. When any user open their database there has an option create table a blank text box there enter table name and 2,3,4 any number in the next box (Number of columns) and click the go button.

Table name rules is same as database name never using space between two words of table name.

Creating table in PHPMyAdmin

There is a student table with 5 numbers of columns. Here columns are field name like student name, address, marks, rollnumber, phone, etc.

Entered name value in the name column like(name, address, marks, rollnumber, phone, etc.)

Then select type of particular column in the type column. Here type means which type of data stored in this field (likename is text value so choose text, address is alphanumeric so choose varchar and phone is numeric so choose int etc)

Then enter length means how many character or digit stored in this column. (like int support 0 to 11 here only store maximum 9 digit because + and – are by default store 2 digits so if any user store number greater than 9 then choose bigint which can store 20 digit maximum. Varchar has 255 character limits. Text has no limit; in text type no need to set length value)

Then set primary key for this table in the index column and click in the save button. In this way a simple table will be created in the database.

No limitation for create table in one database. User can create many table in one database as their require.

Table Structure

Connect PHP with Database

There have some method to connect PHP application with MYSQL database. Like MYSQL, MYSQLi and PDO etc.

Now days MYSQLi is mainly used for connecting database.

Syntax of MYSQLi:

connection.php

Explain:

MYSQLi is a library class for MYSQL database. Using this class manage MYSQL database in a PHP application. There have many functions to display data, store data, delete data and update data of database.

In the above example first parameter is server host name where the database is present by default local server host name is localhost.

Second parameter is server user name which is root in local server.

Third parameter is password value which is null in local server.   

Forth parameter is database name means which particular database is connected with this PHP application.

Here $conn return object of MYSQLi class of particular tutorial database.

mysqli_connect_error() is a pre-define function which check the connection is established successfully or not. If host name user name password database name are wrong then it returns error the stop the PHP execution.

MySQL Insert Data in table

create.php

Output

Add Student Recored (create.php)
PHPMyAdmin Showing student record

Explain:

MYSQL gives insert query for store data in the database.

Insert, into and values are keywords user can write it in any case small or caps. Table name and column name are case sensitive so write same as define.

Execute any MYSQL query used query() function. In above example $sql variable store insert query that’s insert query is executed and one data is stored in the database table. query() function is call by MYSQLi connection object so need to include database connection file. Without database connection never execute any MYSQL query.

Show Data from MySQL Table

show.php

Output:

Showing all students record in show.php

MYSQL gives select query to fetch data from database.

Here * return all columns value of this table. If any user return only specific some column then he/she can write select query like this way, select name, phone, marks from student. Here only name, phone and marks value return.

In above example query() function execute select query so student table selected. Now display the student table’s data, use fetch_array() function which return at a time one row of the table. If user show the all record of the table then call the fetch_array() in a loop. In above example use while loop for fetch all record of the student table.fetch_array() function is return table data as a numeric array and associative array both way. So user can print name value like $rows[name] or $rows[1] both return same result.

Delete Data from MySql Table

MYSQL gives delete query for delete data from database.

delete from tablename.  This query deletes all record of the table. Table will be empty after execute the query. If user want to delete particular one row then add where clause in the delete query. MYSQL support where clause and also AND OR clause.

delete.php

Output:

Student record deleted

Showing record after deleting first record

Now in the student table, only one record left.  The first row deleted from the student table. Always use the primary key column in the where clause. Because the primary key field is store unique value (no duplicate data and no null value) that’s why only exact data will be deleted from the table. If any user use another column in where clause then maybe more than one row will be deleted if value is same in another rows.

Like user use name column then if more than one student name are same then more than one record will be deleted.

Update Data in MySQL table

MYSQL gives update query to update data in the table.

With this query column1, column2 and column3 value are modified by new value for all rows in the table. If user want to update particular one row then use where clause condition in the update query.

update.php

Output:

Student record updated

In the above example address and marks value modified in the one row where rollnumber value is 2.

Inserting Multiple Data

File uplaod form

Uploaded files 

Note:

multiple keyword used to select multiple file at a time.

Getting Last Auto increment ID

<?php echo $conn->insert_id;?>

Its return last auto increment column value. In the file table last inserted id value is 4 so insert_id return 4. Call the insert_id function with the database connection object and write the code after insert query.

Set a column to auto increment value in tableto check A_I option in the table structure.

Column with auto increment 
Select A_I to make column auto increment

Prepare statement to insert data

PDO (PHP Data Objects) is the one of the database connection method to connect MYSQL database to PHP application.

In this method insert query needs to prepare before execute.

prepareinsert.php

Data inserted in table

Explain:

Prepared statements are very useful against SQL injections.

A prepared statement is a feature used to execute the same SQL statements repeatedly with high efficiency.

Prepare: A SQL is created query and data sent to the database. Some values are not specified, they are called parameters. In above example INSERT INTO student VALUES (?, ?, ?, ?, ?) those are parameters.

Database parses the data then compile and finally execute the SQL query, in prepare method data stores in the server without execute.

Execute: In the execute method data combine with parameters and SQL execute the query to store data into database.

 User can execute the query as many times as they want with different values.

Compared to executing SQL statements directly, prepared statements have two main advantages

  1. Prepared method reduces query parsing time for preparing a SQL query.
  2. Bind param minimize bandwidth to the server so website can be load fast and only need to send parameter each time not the whole query.

With Prepared methods SQL query is secured from SQL Injection, because bind param combined the values first then send to the database so no need to be escaped correctly. If the original values are not derived from input then SQL Injection con not occurs.

Please follow and like us:
error

PHP CKEditor Installation and Uses

Write a designable content not possible through HTML form field. That’s why JS create editor which helps user to write designable content in website. Like Gmail use Closure Library JS editor, WordPress support TinyMCE WYSIWYG editor same as PHP support CKEditor, WYMeditor, FCKeditor.

Using this editor user can write blog easily with picture colorful content, admin can add product description with table design, product specification. Admin can write their website content easily by this editor like About Us page content, Privacy Policy, Contact Us, Terms & Condition, etc.

How to Install CKEditor

CKEditor is one of the best useful content editors. It is open source free editor. First need to download this editor.

https://ckeditor.com/ckeditor-5/download/  this is the download link.

After downloading move rar file in the project folder and extract.

Using CKEditor in the project with example

CKEditor for php projects

Use CKEditor in any php script with include external js file ckeditor.js and add class attribute with value ckeditor  in a textarea form element.

After that editor is return in the browser.

CKEditor-PHP-Example

display.php

CKEditor-Example
CKEditor Example

In this example use content_editor table in the test database.

Database-tabel

This is the table structure. Content column always set longtext so user can store large data in this field.

When save editor content data will save in the database with the design of the content not only value that’s why when fetch the database data its return same design as it is.

Mysql Database table

That’s why this editor is very user friendly and useful for website. 

Please follow and like us:
error