Tuesday 27 February 2024

U-WPP-703 (Unit IV: Chapter 8: Database Connectivity with MySQL )

Chapter 8: Database Connectivity with MySQL

8.1 Introduction to RDBMS

8.2 Connection with MySQL Database

8.3 Performing basic database operation(DML) (Insert, Delete, Update, Select)

8.4 Setting query parameter

8.5 Executing query

8.6 Join

8.7 Web Hosting steps

8.1 Introduction to RDBMS:

A database is a separate application that stores a collection of data. Each database has one or more features for creating, accessing, managing, searching and replicating the data it holds.

Other kinds of data stores or data structures can also be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those type of systems.

We use relational database management systems (RDBMS) to store and manage large amount of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as Foreign Keys.

A Relational DataBase Management System (RDBMS) is a software which:

 Enables you to implement a database with tables, columns and indexes.

 Guarantees the Referential Integrity between rows of various tables.

 Updates the indexes automatically.

 Interprets an SQL query and combines information from various tables.

Important terms in RDBMS:

 Database: A database is a collection of tables, with related data.

 Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.

 Column: One column (data element) contains data of one and the same kind, for example the column

rollno.

 Row: A row (= tuple, entry or record) is a group of related data.

 Redundancy: Storing data twice, redundantly to make the system faster.

 Primary Key: A primary key is unique. A key value cannot occur twice in one table. With a key, you can only find one row.

 Foreign Key: A foreign key is the linking pin between two tables.

 Compound Key: A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique.

 Index: An index in a database resembles an index at the back of a book.

 Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an

existing   row.

MySQL Database:

MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is developed, marketed and supported by MySQL AB, which is a Swedish company.

MySQL is becoming so popular because of many good reasons:

 MySQL is released under an open-source license. So you have nothing to pay to use it.

 MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.

 MySQL uses a standard form of the well-known SQL data language.

 MySQL works on many operating systems and with many languages including PHP, PERL, C, C++,

JAVA, etc.

 MySQL works very quickly and works well even with large data sets.

 MySQL is very friendly to PHP, the most appreciated language for web development.

 MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB).

 MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

8.2 Connection with MySql Database:

mysqli_connect() Function:

The mysqli_connect() function in PHP is used to connect you to the database. In the earlier version of the connection mysql_connect() was used for connection and then there comes mysqli_connect() where i means improved version of connection and is more secure than mysql_connect().

Syntax:

mysqli_connect ( "host", "username", "password", "database_name" )

Example:

mysqli_connect("localhost","root","","login");

In this example the mysqli_connect() function connects to "localhost" with the user name "root", an empty password, and selects the "login" database as the default database.

8.3 and 8.4 Performing basic database operation(DML) (Insert, Delete, Update, Select) and Setting query parameter 

Preforming Insert operation on database:

Consider the following script for html interface to accept data from user.

<html>

<head>

<title> Insert operation on database </title>

</head>

<body>

<div id="Logfrm">

<form action="insertsucess.php" method="POST">

<p><label>Roll No: </label>

<input type="text" name="rollno" id="rollno" disabled />

</p>

<p><label>Student Name: </label>

<input type="text" name="studname" id="studname" />

</p>

<p><label>Class: </label>

<input type="text" name="class" id="class" />

</p>

<p><label>Permenant Address: </label>

<input type="text" name="padd" id="padd" />

</p>

<p>

<input type="submit" name="save" id="save" Value="Save" />

</p>

</div>

</form>

</body>

</html>

Consider the following php code to perform insert operation on database “insertsucess.php”.

<?php

//$rollno=$_POST["rollno"];

$studname=$_POST["studname"];

$class=$_POST["class"];

$padd=$_POST["padd"];

$con=mysqli_connect("localhost","root","","login");

if ($con==True){

$query="INSERT INTO `studinfo`( `studname`, `class`, `padd`) VALUES ('$studname','$class','$padd')";

mysqli_query($con,$query);

echo"Record added sucessfully!";

}

else{

echo "fail";

}

mysqli_close($con);

?>

Preforming delete operation on database:

Consider the following php script to select record for delete operation. “remove.php”

<?php

$con=mysqli_connect("localhost","root","","login");

$query="SELECT `rollno` FROM `studinfo`";

$res=mysqli_query($con,$query);

echo "Select Roll number : &nbsp&nbsp&nbsp ";

?>

<html>

<body>

<form action="removed.php" method="get">

<select name="rno">

<?php

$i=0;

while($result=mysqli_fetch_array($res)){

?>

<option> <?php echo $result['rollno'];?></option>

<?php

}

?>

</select>

<input type="submit" name ="btndelete" value="Delete">

</form>

<body>

<html>

Consider the following php script for delete selected record. “removed.php”

<?php

$rollno=$_GET['rno'];

$con=mysqli_connect("localhost","root","","login");

$query="DELETE FROM `studinfo` WHERE `rollno`=$rollno";

$res=mysqli_query($con,$query);

echo "Record deleted! ";

echo "</br>Delete another Record <a href=remove.php>click here </a>";

?>

Preforming update operation on database:

Consider the following php script to select record for update operation. “update.php”

<?php

$con=mysqli_connect("localhost","root","","login");

$query="SELECT `rollno` FROM `studinfo`";

$res=mysqli_query($con,$query);

echo "Select Roll number for update details : &nbsp&nbsp&nbsp ";

?>

<html>

<body>

<form action="showforupdate.php" method="post">

<select name="rno">

<?php

$i=0;

while($result=mysqli_fetch_array($res)){

?>

<option> <?php echo $result['rollno'];?></option>

<?php

}

?>

</select>

<input type="submit" name ="btnshow" value="For Update">

</form>

<body>

<html>

Consider the following php script to show selected record for updating details . “showforupdate.php”

<?php

$rollno=$_POST['rno'];

$con=mysqli_connect("localhost","root","","login");

$query="SELECT * FROM `studinfo` WHERE `rollno`=$rollno";

$res=mysqli_query($con,$query);

$result=mysqli_fetch_array($res);

?>

<html>

<head>

<title>Update Form</title>

</head>

<body>

<div id="Logfrm">

<form action="updated.php" method="POST">

<p><label>Roll No: </label>

<input type="text" name="rollno" id="rollno" value=<?php echo $result['rollno']?> />

</p>

<p><label>Student Name: </label>

<input type="text" name="studname" id="studname"value =<?php echo $result['studname']?> />

</p>

<p><label>Class: </label>

<input type="text" name="class" id="class" value=<?php echo $result['class']?> />

</p>

<p><label>Permenant Address: </label>

<input type="textarea" name="padd" id="padd" maxlength="200" value = <?php echo $result['padd']?> >

</textarea>

</p>

<p>

<input type="submit" name="update" id="update" Value="Update" />

</p>

</div>

</form>

</body>

</html>

Preforming Select operation on database:

Consider the following php script to retrieve all records. “showdata.php”

<?php

$con=mysqli_connect("localhost","root","","login");

$query="SELECT * FROM `studinfo`";

$res=mysqli_query($con,$query);

while($result=mysqli_fetch_array($res)){

echo $result['rollno']." ".$result['studname']." ".$result['class']." ".$result['padd']."</br>";

}

?>

Consider the following php script to retrieve all records in html table. “showdataintable.php”

<?php

$con=mysqli_connect("localhost","root","","login");

$query="SELECT * FROM `studinfo`";

$res=mysqli_query($con,$query);

?>

<html>

<body>

<table border=1px align="center" cellpadding="10" >

<th colspan="4">Student Details</th>

<tr>

<td> Roll Number</td>

<td> Student Name</td>

<td> Class</td>

<td> Permenant Address</td>

</tr>

<?php while($result=mysqli_fetch_array($res)){ ?>

<tr><td><?php echo $result['rollno']?></td>

<td><?php echo $result['studname']?></td>

<td><?php echo $result['class']?></td>

<td><?php echo $result['padd']?></td>

</tr>

<?php

//echo $result['rollno']." ".$result['studname']." ".$result['class']." ".$result['padd']."</br>";

}

?>

</table>

</body>

</html>

8.5 Executing query:

mysqli_query() function performs a query against a database.

Syntax:

mysqli_query(connection, query, resultmode)

Parameters:

 connection: this parameter is required; it specifies the MySQL connection to use.

 query: this is also compulsory parameter; it specifies the SQL query string.

 resultmode: it is Optional parameter. it Can be one of the following:

o MYSQLI_USE_RESULT (Use this to retrieve large amount of data)

o MYSQLI_STORE_RESULT (This is default)

Example:

mysqli_query($con,$query)

8.6 Join:

MySQL joins:

MySQL join clause combines records from two or more tables in a relational database. It creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables (or more) by using values common to each. 

MySQL specifies four types of JOIN: INNER, LEFT OUTER, RIGHT OUTER, and CROSS INNER JOIN:

The MySQL Inner join only displays the matching records from Table A and Table B (Like an Intersect in Mathematics).

Syntax:

SELECT Table1.Column(s), Table2.Column(s)

FROM Table1

INNER JOIN

Table2 ON

Table1.Common_Column = Table2.Common_Column

database: Login

dept emp

deptid deptname empid empname empsalary deptid

Example:

SELECT emp.empid,emp.empname,emp.empsal,dept.deptname FROM emp INNER JOIN dept ON

emp.deptid=dept.deptid

MySQL Left Join or Left outer join:

MySQL Left Join or Left outer join is to return all the records (or rows) from the Left table, and matching rows from the right table.

Syntax:

SELECT Table1.Column(s), Table2.Column(s)

FROM Table1

LEFT JOIN

Table2 ON

Table1.Common_Column = Table2.Common_Column

Example:

SELECT emp.empid,emp.empname,emp.empsal,dept.deptname FROM emp INNER JOIN dept ON

emp.deptid=dept.deptid

Example:

SELECT * FROM emp LEFT JOIN dept ON emp.deptid=dept.deptid

MySQL Right Outer Join:

MySQL Right Outer Join is one of the Join Type, which is useful to return all the existing records (or rows) from the Right table, and matching rows from the left table. All the Unmatched rows from the left table filled with NULL Values.

Syntax:

SELECT Table1.Column(s), Table2.Column(s)

FROM Table1

RIGHT JOIN

Table2 ON

Table1.Common_Column = Table2.Common_Column

Example:

SELECT * FROM emp RIGHT JOIN dept ON emp.deptid=dept.deptid

MySQL Cross Join:

MySQL Cross Join returns the Cartesian product of both the tables. The Cross Join in MySQL does not require any

common column to join two tables. The Cartesian product means Number of Rows present in Table 1 Multiplied by

Number of Rows present in Table 2.

Syntax:

SELECT Table1.Column(s), Table2.Column(s),

FROM Table1

CROSS JOIN

Table2

Example:

SELECT * FROM `studinfo` CROSS JOIN `user`

U-WPP-703 (UNIT – IV: Chapter 7 Introduction to OOPS )

 UNIT – IV Chapter 7 Introduction to OOPS

7.1 Class, Objects, Constructor, Destructor

7.2 Access method and properties using $this variable

7.3 Public, private, protected properties and methods

7.4 Static properties and method

7.5 Inheritance & code reusability

7.6 Polymorphism

7.7 Parent:: & self:: keyword

7.8 Instanceof operator

7.9 Interface

Introduction to OOPS:

PHP is a server-side scripting language, mainly used for web development but also used as a

general-purpose programming language. Object-Oriented Programming (PHP OOP), is a type of

programming language principle added to php5, that helps in building complex, reusable web

applications.

The Object Oriented concepts in PHP are:

● Class: It is a programmer defined data type, which includes local functions as well as

local data. You can think of a class as a template for making many instances of the same

kind (or class) of object.

● Object: An individual instance of the data structure defined by a class. You define a class

once and then make many objects that belong to it. Objects are also known as instance.

● Inheritance: When a class is defined by inheriting existing function of a parent class

then it is called inheritance. Here child class will inherit all or few member functions and

variables of a parent class.

● Polymorphism: This is an object oriented concept where the same function can be used

for different purposes. simply, a function name will remain the same but it makes a

different number of arguments and can do different tasks.

● Overloading: Overloading is a type of polymorphism in which some or all of operators

have different implementations depending on the types of their arguments. Similarly,

functions can also be overloaded with different implementation.

● Data Abstraction: Any representation of data in which the implementation details are

hidden (abstracted). Encapsulation refers to a concept where we encapsulate all the data

and member functions together to form an object.

● Constructor: It refers to a special type of function which will be called automatically

whenever there is an object formation from a class.

● Destructor: It refers to a special type of function which will be called automatically

whenever an object is deleted or goes out of scope.

7.1 Class, Objects, Constructor, Destructor:

Class

Classes are the blueprints of objects. One of the big differences between functions and classes is

that a class contains both data (variables) and functions that form a package called an: ‘object’.

Class is a programmer-defined data type, which includes local methods and local variables. Class

is a collection of objects. Object has properties and behavior.

Object:

The fundamental idea behind an object-oriented language is to enclose a bundle of variables and

functions into a single unit and keep both variables and functions safe from outside interference

and misuse. Such a unit is called an object which acts on data.

The mechanism that binds together data and functions are called encapsulation. This feature

makes it easy to reuse code in various projects. The functions declared in an object provides the

way to access the data. The functions of an object are called methods and all the methods of an

object have access to variables called properties.

Creating classes and objects (Instantiation):

The class definition starts with the keyword class followed by a class name, then followed by a

set of curly braces ({}) which enclose constants, variables (called "properties"), and functions

(called "methods") belonging to the class.

· A valid class name (excluding the reserved words) starts with a letter or

underscore, followed by any number of letters, numbers, or underscores.

· Class names usually begin with an uppercase letter to distinguish them from other

identifiers.

· An instance is an object that has been created from an existing class.

· Creating an object from an existing class is called instantiating the object.

· To create an object out of a class, the new keyword must be used.

· Classes should be defined prior to instantiation.

Syntax:

<?php

class Myclass

{

// Add property statements here

// Add the methods here

}

?>

In the following example keyword new is used to instantiate an object. Here $myobj represents

an object of the class Myclass.

<?php

$myobj = new MyClass;

?>

The contents of the class Myclass using var_dump() function display structured information

(type and value) about one or more variables:

<?php

class Myclass

{

// Add property statements here

// Add the methods here

}

$myobj = new MyClass;

var_dump($myobj);

?>

Output:

object(Myclass)#1 (0) { }

Setting Properties

Class member variables are called properties. Sometimes they are referred as attributes or fields.

The properties hold specific data and related with the class in which it has been defined.

Declaring a property in a class is an easy task, use one of the keyword public, protected, or

private followed by a normal variable declaration.

● public: The property can be accessed from outside the class, either by the script or from

another class.

● private: No access is granted from outside the class, either by the script or from another

class.

● protected: No access is granted from outside the class except a class that’s a child of the

class with the protected property or method.

Example:

After an object is instantiated, you can access the property of a class using the object and ->

operator. Any member declared with keyword "private" or "protected" cannot be accessed

outside the method of the class.

Simpleclass.php

<?php

class Myclass

{

public $font_size =10;

}

$f = new MyClass;

echo $f->font_size;

?>

Setting Methods:

The functions which are declared in a class are called methods.

A class method is exactly similar to PHP functions.

❏ Declaring a method in a class is an easy task, use one of the keyword public, protected, or

private followed by a method name.

❏ public : The method can be accessed from outside the class.

❏ private : No access is granted from outside the class.

❏ protected : No access is granted from outside the class except a class that’s a child

of the class with the protected property or method.

❏ A valid method name starts with a letter or underscore, followed by any number of

letters, numbers, or underscores.

❏ The method body enclosed within a pair of braces which contains codes. The opening

curly brace ( { ) indicates the beginning of the method code and the closing curly ( } )

brace indicates the termination of the method.

❏ If the method is not defined by public, protected, or private then default is public.

❏ Can access properties and methods of the current instance using $this (Format

$this->property) for non static property.

Example:

After an object is instantiated, you can access the method of a class using the object and

->(“object operator”) operator. In the following example customize_print() method will print a

string with a specific font size and color within a html paragraph element with the help of php

echo statement.

<?php

class Myclass

{

public $font_size ="18px";

public $font_color = "blue";

public $string_name = "Rajarshi Shahu College (Autonomous), Latur";

public function customize_print()

{

echo "<p

style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_name."</p>";

}

}

$f = new MyClass;

//$f->font_size="50px";

//$f->font_color="red";

//$f->string_name="Programming With PhP";

echo $f->customize_print();

?>

7.2 Access method and properties using $this variable:

During the execution of an object’s method, a special variable called $this is automatically

defined, which denotes a reference to the object itself. By using this variable and the -> notation,

the object’s methods and properties can be further referenced. For example, you can access the

$name property by using $this->name (note that you don’t use a $ before the name of the

property). An object’s methods can be accessed in the same way; for example, from inside one of

person’s methods, you could call getName() by writing $this->getName().

7.3 Public, private, protected properties and methods

Methods can be public, private or protected. Public means that methods can be accessed

everywhere, private means methods can be accessed by the class that defines the member and

protected means methods can be accessed only within the class itself and by inherited and parent

classes.

<?php

// Define a class

class Myclass

{

// Declare a public method

public function my_public_method()

{

echo "This is a Public method";

}

private function my_private_method()

{

echo "This is a Private method";

}

protected function my_protected_method()

{

echo "This is a Protected method";

}

// This is public

function test()

{

$this->my_public_method();

$this->my_private_method();

$this->my_protected_method();

}

}

$obj = new MyClass;

$obj->my_public_method(); //Display This is a Public method

$obj->my_private_method();//Fatal error: Call to private method

Myclass::my_private_method() C:\xampp\htdocs\srss\chap7\ppp.php:28 Stack trace: #0 {main}

thrown in C:\xampp\htdocs\srss\chap7\ppp.php on line 28

$obj>my_protected_method();//Fatal error: Call to undefined function my_protected_method()

in C:\xampp\htdocs\srss\chap7\ppp.php:29 Stack trace: #0 {main} thrown in

C:\xampp\htdocs\srss\chap7\ppp.php on line 29

$obj->test(); //Display This is a Public methodThis is a Private methodThis is a Protected

method

?>

Constructors and Destructors:

When creating a new object, often it’s useful to set up certain aspects of the object at the same time. For example,

you might want to set some properties to initial values, fetch some information from a database to populate the

object, or register the object in some way.

Similarly, when it’s time for an object to disappear, it can be useful to tidy up aspects of the object, such as closing

any related open files and database connections, or unsetting other related objects.

Like most OOP languages, PHP provides you with two special methods to help with these tasks. An object’s

constructor method is called just after the object is created, and its destructor method is called just before the object

is freed from memory.

PHP Constructor methods:

● Constructors allow to initializing object properties ( i.e. the values of properties) when an object is created.

● Classes which have a constructor method execute automatically when an object is created.

● The 'construct' method starts with two underscores (__).

● The constructor is not required if you don't want to pass any property values or perform any actions when

the object is created.

● PHP only ever calls one constructor.

The general syntax for constructor declaration follows:

function __construct([argument1, argument2, ..., argumentN])

{

/* Class initialization code */

}

The type of argument1, argument2,.......,argumentN are mixed.

Construct.php

<?php

// Define a class

class Myclass

{

// Declaring three private varaibles

private $font_size;

private $font_color;

private $string_value;

// Declarte construct method which accepts three parameters

function __construct($font_size,$font_color,$string_value)

{

$this->font_size = $font_size;

$this->font_color = $font_color;

$this->string_value = $string_value;

}

// Declare a method for customize print

function customize_print()

{

echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";

}

}

// Create a new object and passes three parameters

$f = new MyClass('20px','red','Programming with PhP');

// Call the method to display the string

echo $f->customize_print();

?>

Like properties, constructors can call class methods or other functions. In the following example there is no need to

call the method separately (after creating the object and passing the parameters, see the previous example) as it is

already declared within the constructor. See the following example :

<?php

// Define a class

class Myclass

{

// Declaring three private variables

private $font_size;

private $font_color;

private $string_value;

// Declarte construct method which accepts three parameters and the method customize_print()

function __construct($font_size,$font_color,$string_value)

{

$this->font_size = $font_size;

$this->font_color = $font_color;

$this->string_value = $string_value;

$this->customize_print();

}

// Declare a method for customize print

function customize_print()

{

echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";

}

}

// Create a new object and passes three parameters

$f = new MyClass('20px','red', 'Programming with PhP');

?>

PHP Destructors methods:

● The destructor is the counterpart of constructor.

● A destructor function is called when the object is destroyed

● A destructor function cleans up any resources allocated to an object after the object is destroyed.

● A destructor function is commonly called in two ways: When a script ends or manually delete an object

with

● the unset() function

● The 'destructor' method starts with two underscores (__).

The general syntax for destructor declaration follows :

function __destruct

{

/* Class initialization code */\

}

The type of argument1, argument2,.......,argumentN are mixed.

Example:

<?php

// Define a class

class MyClass

{

function __construct()

{

echo 'w3resource'.'<br>';

$this->name = "MyClass";

}

function __destruct()

{

echo "Destroying… " . $this->name . "<br>";

}

}

$obj = new MyClass();

?>

7.4 Static properties and method:

Static properties:

Static properties can be called directly - without creating an instance of a class.

Static properties are declared with the static keyword:

Syntax

<?php

class ClassName {

public static $staticProp = "rsml";

}

?>

To access a static property use the class name, double colon (::), and the property name:

Syntax

ClassName::staticProp;

Let's look at an example:

Example

<?php

class pi {

public static $value = 3.14159;

}

// Get static property

echo pi::$value;

?>

Static methods:

Static methods can be called directly - without creating an instance of a class.

Static methods are declared with the static keyword:

Syntax

<?php

class ClassName {

public static function staticMethod() {

echo "Hello World!";

}

}

?>

To access a static method use the class name, double colon (::), and the method name:

Syntax

ClassName::staticMethod();

Example

<?php

class greeting {

public static function welcome() {

echo "Hello World!";

}

}

// Call static method

greeting::welcome();

?>

7.5 Inheritance & code reusability:

To inherit the properties and methods from another class, use the extends keyword in the class definition, followed

by the name of the base class:

class Person

{

public $name, $address, $age;

}

class Employee extends Person

{

public $position, $salary;

}

The Employee class contains the $position and $salary properties, as well as the $name, $address, and $age

properties inherited from the Person class.

If a derived class has a property or method with the same name as one in its parent class, the property or method in the derived class takes precedence over the property or method in the parent class. Referencing the property returns the value of the property on the child, while referencing the method calls the method on the child.

To access an overridden method on an object’s parent class, use the parent:: method() notation:

parent::birthday(); // call parent class's birthday() method

A common mistake is to hardcode the name of the parent class into calls to overridden methods:

Creature::birthday(); // when Creature is the parent class This is a mistake because it distributes knowledge of the parent class’s name throughout the derived class. 

Using parent:: centralizes the knowledge of the parent class in the extends clause.

If a method might be subclassed and you want to ensure that you’re calling it on the current class, use the self::method() notation:

self::birthday(); // call this class's birthday() method

7.6 Polymorphism:

Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism is one of the PHP Object Oriented Programming (OOP) features. In general, polymorphism means the ability to have many forms. If we say it in other words, "Polymorphism describes a pattern in Object Oriented Programming in which a class has varying functionality while sharing a common interface.". 

There are two types of Polymorphism; they are:

1. Compile time (function overloading)

2. Run time (function overriding)

But PHP "does not support" compile time polymorphism.

Runtime polymorphism

The Runtime polymorphism means that a decision is made at runtime (not compile time) or we can say we can have multiple subtype implements for a super class, function overloading is an example of runtime polymorphism. I will first describe function overloading. When we create a function in a derived class with the same signature (in other words a function has the same name, the same number of arguments and the same type of arguments) as a function in its parent class then it is called method overriding.

Example:

<?php

interface Shape {

public function calcArea();

}

class Circle implements Shape {

private $radius;

public function __construct($radius)

{

$this -> radius = $radius;

}

// calcArea calculates the area of circles

public function calcArea()

{

return $this -> radius * $this -> radius * pi();

}

}

class Rectangle implements Shape {

private $width;

private $height;

public function __construct($width, $height)

{

$this -> width = $width;

$this -> height = $height;

}

// calcArea calculates the area of rectangles

public function calcArea()

{

return $this -> width * $this -> height;

}

}

$circ = new Circle(3);

$rect = new Rectangle(3,4);

echo $circ -> calcArea();

echo "</br>";

echo $rect -> calcArea();

?>

7.7 Parent:: & self:: keyword:

PHP supports two reserved class names that make it easier when writing OO applications. self:: refers to the current class and it is usually used to access static members, methods, and constants. parent:: refers to the parent class and it is most often used when wanting to call the parent constructor or methods. It may also be used to access members and constants. You should use parent:: as opposed to the parent’s class name because it makes it easier to change your class hierarchy because you are not hard-coding the parent’s class name. 

The following example makes use of both parent:: and self:: for accessing the Child and Ancestor classes: 

<?php

class pen {

const NAME = "Cello";

function __construct()

{

echo "In " . self::NAME . " constructor </br>";

}

}

class Child extends pen {

const NAME = "Cello greeper";

function __construct()

{

parent::__construct();

echo "In " . self::NAME . " constructor";

}

}

$obj = new Child();

?>

The previous example outputs

In Ancestor constructor

In Child constructor 

Make sure you use these two class names whenever possible.

7.8 Instanceof operator:

The instanceof operator is used in PHP to find out if an object is an instantiated instance of a class.

Syntax:

$a instanceof MyClass

Operands: This operator contains two operands which are listed below:

· $a: This is used as an object.

· MyClass: It is a class name.

Return Value: It returns True if the object is of this class or has this class as one of its parents else it will return a

False value.

<?php

// PHP program to illustrate instanceof

// operator

// sample class

class student{

var $store = 'Hello students!';

}

// create a new object

$stud = new studdents();

// Checks if $stud is an object of class students

if ($stud instanceof students) {

echo "Yes";

}

?>

Output: Yes

7.9 Interface:

Interfaces provide a way for defining contracts to which a class adheres; the interface provides method prototypes and constants, and any class that implements the interface must provide implementations for all methods in the interface. Here’s the syntax for an interface definition:

interface interfacename

{

[ function functionname();

...

]

}

To declare that a class implements an interface, include the implements keyword and any number of interfaces,

separated by commas:

interface Printable

{

function printOutput();

}

class ImageComponent implements Printable

{

function printOutput()

{

echo "Printing an image...";

}

}

An interface may inherit from other interfaces (including multiple interfaces) as long as none of the interfaces it inherits from declare methods with the same name as those declared in the child interface.

U-WPP-703 (Unit III: Chapter VI: String matching with regular expression )

 Syllabus: Unit III: Chapter VI: String matching with regular expression

6.1 What is regular expression

6.2 Pattern matching in Php

6.3 Replacing text

6.4 Splitting a string with a Regular Expression

6.1 What is regular expression:

Regular expressions are powerful pattern matching algorithm that can be performed in a single expression.

Regular expressions use arithmetic operators such as (+,-,^) to create complex expressions.

Regular expressions help you accomplish tasks such as validating email addresses, IP address etc.

Use of regular expressions:

 Regular expressions simplify identifying patterns in string data by calling a single function. This

saves us coding time.

 When validating user input such as email address, domain names, telephone numbers, IP

addresses, Highlighting keywords in search results

 When creating a custom HTML template. Regular expressions can be used to identify the template

tags and replace them with actual data.

PHP has built in functions that allow us to work with regular functions. Let’s now look at the commonly used

regular expression functions in PHP.

preg_match : this function is used to perform a pattern match on a string. It returns true if a match is found and

false if a match is not found.

preg_split : this function is used to perform a pattern match on a string and then split the results into a numeric

array

preg_replace : this function is used to perform a pattern match on a string and then replace the match with the

specified text.

Following is the syntax for a regular expression function such as preg_match,preg_split or preg_replace.

<?php

function_name('/pattern/',subject);

?>

 "function_name(...)" is either preg_match, preg_split or preg_replace.

 "/.../" The forward slashes denote the beginning and end of our regular expression

 "'/pattern/'" is the pattern that we need to matched

 "subject" is the text string to be matched against

6.2 Pattern matching in Php:

PHP Preg_match:

The first example uses the preg_match function to perform a simple pattern match for the word latur in a given

URL.

The code below shows the implementation for the above example.

<?php

$my_url = "www.shahucollegelatur.org.in";

if (preg_match("/latur/", $my_url))

{

echo "the url $my_url contains latur";

}

else

{

echo "the url $my_url does not contain latur";

}

?>

6.3 Replacing text:

PHP Preg_replace:

Let’s now look at the preg_replace function that performs a pattern match and then replaces the pattern with

something else.

The code in following example searches for the word do in a string.

It replaces the word do with the word end.

<?php

$text = "Politics always change. Stories never do.";

$text = preg_replace("/do/", 'end', $text);

echo $text;

?>

6.4 Splitting a string with a Regular Expression

PHP Preg_split:

We will take a string phrase and explode it into an array; the pattern to be matched is a single space.

The text string to be used in this example is " This is my college ".

Example.

<?php

$my_text="This is my college";

$my_array = preg_split("/ /", $my_text);

print_r($my_array );

?>

U-WPP-703 ( UNIT – III: Chapter 5 - State management)

 UNIT – III: Chapter 5 - State management

5.1 Using query string(URL rewriting)

5.2 Using Hidden field

5.3 Using cookies

5.4 Using session

Introduction to State Management:

HTTP is a stateless protocol which means every user request is processed independently and it has nothing to do

with the requests processed before it. Hence there is no way to store or send any user specific details using HTTP

protocol.

But in modern applications, user accounts are created and user specific information is shown to different users, for

which we need to have knowledge about who the user (or what he/she wants to see etc.) is on every webpage.

PHP provides for two different techniques for state management of your web application, they are:

1. Server Side State Management

2. Client Side Server Management

Server Side State Management

In server side state management, we store user specific information required to identify the user on the server and

this information is available on every webpage.

In PHP we have Sessions for server side state management. PHP session variable is used to store user session

information like username, userid etc. and the same can be retrieved by accessing the session variable on any

webpage of the web application until the session variable is destroyed.

Client Side State Management

In client side state management, the user specific information is stored at the client side i.e. in the bowser. Again,

this information is available on all the webpages of the web application.

In PHP we have Cookies for client side state management. Cookies are saved in the browser with some data and

expiry date (till when the cookie is valid).

One drawback of using cookie for state management is the user can easily access the cookie stored in their browser

and can even delete it.

5.1 Using query string (URL rewriting): [306]

Most of the Web applications you use today have a need to store data between browser requests. For example, a

shopping cart needs to remember which items you have added to your cart. A forum application needs to remember

your identity whenever you post a message in the forum.

In other words, there is a need to preserve the current state of a user’s interaction with an application from one

request to the next. Query strings are a quick, convenient way to pass small amounts of data between browser

requests. Common uses of query strings include remembering a user’s entered keywords when using a search

function, identifying which topic within a forum to display to the user, and specifying which post within a blog to

display.

Query string data is very easy for the user to alter, because it’s visible and editable within the browser’s

address bar. Therefore, query strings should be used only in situations where sending incorrect data won’t

compromise security. For example, don’t use query strings for storing things such as user IDs. When the form data

is sent to the server, it is appended to the end of the URL as follows:

http://localhost/myscript.php?firstName=Fred & lastName=Bishop & ...

The browser adds a query (?) character to the end of the URL, then follows it with each of the form fields as

“name=value” pairs, with each pair separated by an ampersand (&). The query string is the part of the URL after

the? character.

Query strings not limited to form data. Because a query string is simply a string of characters stored in a URL, you

can manually create a URL containing a query string in your PHP script, then include the URL as a link within the

displayed page or in an email, for example. PHP even provides some built - in functions to make the process easier.

Here’s a simple example that creates two variables, $firstName and $age, then creates a link in the displayed page

that contains a query string to store the variable values:

<html>

<body>

<?php

$firstName = "John";

$age = "34";

$queryString = "firstName=$firstName&age=$age";

echo '<p><a href="moreinfo.php?' . $queryString . '" > Find out more info on this person </a> </p >';

?>

</body>

</html>

This code generates the following markup:

< p > < a href= “moreinfo.php?firstName=John&age=34”> Find out more info on this person < /a > < /p >

If the user then clicks this link, moreinfo.php is run, and the query string data ( firstName=John & age=34 ) is

passed to the moreinfo.php script. Data has been transmitted from one script execution to the next.

The ampersand ( & ) character needs to be encoded as & amp; inside XHTML markup.

One thing to watch out for is the type of characters that you insert into the field names and values in your query

string.

The specifications for a query string allows only the following characters to be used within field names and values:

letters, numbers, and the symbols - , , . (period), ! , ~ , * , ‘ (single quote), ( , and ) .

So what do you do if you need to transmit other characters, such as spaces, curly braces, or? characters? The answer

is that you should use URL encoding. This is a scheme that encodes any reserved characters as hexadecimal

numbers preceded by a percent ( % ) symbol, with the exception of space characters, which are encoded as plus ( + )

signs.

PHP gives you a function called urlencode() that can encode any string using URL encoding. Simply pass it a string

to encode, and it returns the encoded string. So you can use urlencode() to encode any data that may contain

reserved characters.

Here’s an example:

<html>

<body>

<?php

$firstName = "John";

$homePage = "http://www.shahucollege.com/";

$favoriteSport = "Ice Hockey";

$queryString = "firstName=" . urlencode($firstName) . " & amp;homePage=" .urlencode( $homePage ) . "

&amp;favoriteSport=" . urlencode( $favoriteSport );

echo '<p><a href="moreinfo.php?'.$queryString .'"> Click to more information </a></p>';

?>

</body>

</html>

This code snippet outputs the following markup:

<p><a href=”moreinfo.php?firstName=John%20&%20amp;homePage=http%3A%2F%2Fwww.shahucollege.com%2F%20

&favoriteSport=Ice+Hockey” ” > Find out more info on this person < /a > < /p >

Accessing Data in Query Strings

As you’ve probably guessed by now, to access the field names and values in a query string you simply read

them from the $_GET superglobal array, just as if you were handling a form sent with the get method:

$firstName = $_GET[“firstName”];

$homePage = $_GET[“homePage”];

So it’s easy to write a simple version of the moreinfo.php script referenced in the previous example:

< ?php

$firstName = $_GET[“firstName”];

$homePage = $_GET[“homePage”];

$favoriteSport = $_GET[“favoriteSport”];

echo “ < dl > ”;

echo “ < dt > First name: < /dt > < dd > $firstName < /dd > ”;

echo “ < dt > Home page: < /dt > < dd > $homePage < /dd > ”;

echo “ < dt > Favorite sport: < /dt > < dd > $favoriteSport < /dd > ”;

echo “ < /dl > ”;

? >

5.2 Using Hidden field:

A hidden field let web developers include data that cannot be seen or modified by users when a form is submitted.

A hidden field often stores what database record that needs to be updated when the form is submitted.

While the value is not displayed to the user in the page's content, it is visible (and can be edited) using any browser's

developer tools or "View Source" functionality. Do not use hidden inputs as a form of security!

The numbers browser that fully supports the hidden element are chrome, internet browser, safari, firefox, opera etc.

The <input type="hidden"> defines a hidden input field.

<html>

<body>

<h1>Using hidden input field:</h1>

<form action="/customerid.php">

First name: <input type="text" name="fname"><br>

<input type="hidden" id="custId" name="custId" value="501">

<input type="submit" value="Submit">

</form>

<p>Notice that the hidden input field is not shown to the user, but the data is sent when the form is submitted.</p>

</body>

</html>

5.3 Using cookies:

A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer. They are

typically used to keeping track of information such as a username that the site can retrieve to personalize the page

when the user visits the website next time. A cookie can only be read from the domain that it has been issued from.

Simply a cookie is a message given to a Web browser by a Web server. The browser stores the message in a small

text file that the server embeds on the user's computer. Each time the same computer requests a page with a browser,

the cookie is sent back to the server too.

There are a wide variety of things you can do with cookies. They are used to store information about user, visited

pages, poll results and etc. The main purpose of cookies is to identify users and possibly prepare customized Web

pages for them.

Normally cookies are used only to store small amounts of data. Websites can read the values from the cookies and

use the information as desired. In addition to the information it stores, each cookie has a set of attributes that helps

ensure the browser sends the correct cookie when a request to a server is made.

Even though cookies are not harmful some people do not permit cookies due to concerns about their privacy. In this

case you have to use Sessions.

Creating a Cookie:

PHP cookies can be set using the setcookie() function. The syntax is as follows:

setcookie(name[, value[, expire[, path[, domain[, security]]]]])

 [name] The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.

 [value] The cookie value. It is associated with the cookie name. [expire] The time after which the cookie

should expire in seconds.

 [path] Specifies the exact path on the domain that can use the cookies.

 [domain] The domain that the cookie is available. If not domain is specified, the default value is the value

of the domain in which cookie was created.

 [security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the cookie is

sent over a secure connection but it doesn't mean that the cookie is secure. It's just a text file like every

other cookie. A value of 0 denotes a standard HTTP transmission.

In the example below, we will create a cookie named "myCookie" and assign the value "FirstCookie" to it. We also

specify that the cookie should expire after one hour and that the cookie is available for all pages within a Tutorials

directory.

<?php

setcookie("myCookie", " FirstCookie ", time()+3600, "/tutorials");

?>

There's one important item to mention about using cookies. Because of the way cookies work within HTTP, it's

important that you send all cookies before any output from your script. This requires that you place calls to this

function before any output, including tags as well as any whitespace. If you don't, PHP will give you a warning and

your cookies will not be sent.

Retrieving a Cookie Data:

Now the cookie is set and we need to retrieve the information. As mentioned above the name of each cookie sent by

your server accessed with the superglobal array $_COOKIE. In the example below we retrieve the value of the

cookie and print out its value on the screen.

<?php

echo "The cookie value is ".$_COOKIE['myCookie'];

?>

This would show up on the page as: "myCookie value is FirstCookie".

Deleting a Cookie:

By default, the cookies are set to be deleted when the browser is closed. We can override that default by setting a

time for the cookie's expiration but there may be occasions when you need to delete a cookie before the user closes

his browser, and before its expiration time arrives. To do so, you should assure that the expiration date is in the past.

The example below demonstrates how to do it (setting expiration time 1 minute ago):

<?php

setcookie("myCookie", "", time()-60);

?>

Example:

htmlform.html

<html>

<body>

<form action="dispinfo.php" method="post">

<label> Enter Student Name:</label>

<input type="text" name="sname"></br>

<label> Enter Roll No:</label>

<input type="text" name="srno"></br>

<label> Enter Class:</label>

<input type="text" name="sclass"></br>

<label> Enter Semester:</label>

<input type="text" name="sem"></br>

<input type="submit" name="submit" value="submit">

</form>

</body>

</html>

Displaying Information and Setting Cookie:

dispinfo.php

<?php

$sname=$_POST["sname"];

$srno=$_POST["srno"];

$sclass=$_POST["sclass"];

$sem=$_POST["sem"];

echo "Student Name:".$sname."</br>";

echo "Student Roll No:".$srno."</br>";

echo "Student Class:".$sclass."</br>";

echo "Student Semester:".$sem."</br>";

setcookie("studcookie",$_POST["sname"]." ".$_POST["srno"]." ".$_POST["sclass"]."

".$_POST["sem"],time()+3600);

echo "cookies set Successfully! ";

?>

Accessing Cookie Data:

<html><body>

<?php

#accessing cookie values and removing cookie

echo "The cookie value is : ".$_COOKIE['studcookie']."</br>";

echo "Cookie accessed successfully</br>";

?>

<a href="/srss/clear.php">Click Here to delete cookie</a>

</body></html>

Deleting or removing cookie:

<?php

setcookie("studcookie","",time()+3600);

echo "Cookie Deleted Successfully!";

?>

5.4 Using session:[340]

Although you can store data using cookies but it has some security issues. Since cookies are stored on user's

computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful data in your

application that might break your application.

Also every time the browser requests a URL to the server, all the cookie data for a website is automatically sent to

the server within the request. It means if you have stored 5 cookies on user's system, each having 4KB in size, the

browser needs to upload 20KB of data each time the user views a page, which can affect your site's performance.

You can solve both of these issues by using the PHP session. A PHP session stores data on the server rather than

user's computer. In a session based environment, every user is identified through a unique number called session

identifier or SID. This unique session ID is used to link each user with their own information on the server like

emails, posts, etc.

Starting a PHP Session:

Before you can store any information in session variables, you must first start up the session. To begin a new

session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID

for the user.

The PHP code in the example below simply starts a new session.

<?php

session_start();

?>

The session_start() function first checks to see if a session already exists by looking for the presence of a session ID.

If it finds one, i.e. if the session is already started, it sets up the session variables and if doesn't, it starts a new

session by creating a new session ID.

The session_start() function must call at the beginning of the page i.e. before any output generated by your script in

the browser.

Storing and Accessing Session Data:

You can store all your session data as key-value pairs in the $_SESSION[] superglobal array. The stored data can be

accessed during lifetime of a session. Consider the following script, which creates a new session and registers two

session variables.

<?php

session_start();

$_SESSION["firstname"] = "Peter";

$_SESSION["lastname"] = "Parker";

?>

To access the session data we set on our previous example from any other page on the same web domain — simply

recreate the session by calling session_start() and then pass the corresponding key to the $_SESSION associative

array.

<?php

session_start();

// Accessing session data

echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];

?>

Destroying or Removing a Session:

If you want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array,

as shown in the following example:

<?php

session_start();

// Removing session data

if(isset($_SESSION["lastname"])){

unset($_SESSION["lastname"]);

}

?>

However, to destroy a session completely, simply call the session_destroy() function. This function does not need

any argument and a single call destroys all the session data.

<?php

session_start();

// Destroying session

session_destroy();

?>

Every PHP session has a timeout value. Timeout value is a duration, measured in seconds, which determines how

long a session should remain alive in the absence of any user activity.

Example:

<?php

session_start();

if(isset($_SESSION["count"])) {

$accesses = $_SESSION["count"] + 1;

} else {

$accesses = 1;

}

$_SESSION["count"] = $accesses;

// session_destroy();

?>

<html>

<head>

<title>Access counter</title>

</head>

<body>

<h1>Access counter</h1>

<p>You have accessed this page <?php echo $accesses; ?> times today.</p>

<p>[<a href="session.php">Reload</a>]</p>

</body>

</html>

==0==

U-WPP-703 (UNIT – II: Chapter 4 - Array )

 

UNIT – II: Chapter 4 - Array
4.1 Anatomy of an Array
4.2 Creating index based and Associative array
4.3 Accessing array Element
4.4 Looping with Index based array
4.5 Looping with associative array using foreach()
4.1 Anatomy of an Array
There are three different kind of arrays:
·        Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
·        Associative array - An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
·        Multidimensional array - An array containing one or more arrays and values are accessed using multiple indices

4.2 Creating index based and Associative array:
Arrays in PHP are easy to create. The simplest way to create a new array variable is to use PHP s built - in array() construct. This takes a list of values and creates an array containing those values, which you can then assign to a variable:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );

In this line of code, an array of four elements is created, with each element containing a string value. The array is then assigned to the variable $authors.
You can now access any of the array elements via the single variable name, $authors. This array is an indexed array, which means that each of the array elements is accessed via its own numeric index, starting at zero.
Here, the “Steinbeck” element has an index of 0 , “ Kafka ” has an index of 1 , “ Tolkien ” has an index of 2 , and “ Dickens ” has an index of 3 .

If you want to create an associative array, where each element is identified by a string index rather than a number, you need to use the => operator, as follows:

$myBook = array( “title” = > “The Grapes of Wrath”, “author” = > “John Steinbeck”, “pubYear” = > 1939 );

This creates an array with three elements: “ The Grapes of Wrath ” , which has an index of “ title “ ; “ John Steinbeck ”, which has an index of “ author “ ; and 1939 , which has an index of “ pubYear ”.

4.3 Accessing Array Elements:
Once you’ve created your array, how do you access the individual values inside it? In fact, you do this in much the same way as you access the individual characters within a string:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$myAuthor = $authors[0]; // $myAuthor contains “Steinbeck”
$anotherAuthor = $authors[1]; // $anotherAuthor contains “Kafka”

In other words, you write the variable name, followed by the index of the element in square brackets. If you want to access the elements of an associative array, simply use string indices rather than numbers:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
$myTitle = $myBook[“title”]; // $myTitle contains “The Grapes of Wrath”
$myAuthor = $myBook[“author”]; // $myAuthor contains “Steinbeck”

You don’t have to use literal values within the square brackets; you can use any expression, as long as it
evaluates to an integer or string as appropriate:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$pos = 2;
echo $authors[$pos + 1]; // Displays “Dickens”

Changing Elements
In addition to accessing the array values you can change values using the same techniques.
For example, the following code changes the value of the third element in an indexed array from “ Tolkien ” to “ Melville “ :

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[2] = “Melville”;

What if you wanted to add a fifth author? You can just create a new element with an index of 4,
as follows:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[4] = “Orwell”;

There’s an even easier way to add a new element to an array — simply use square brackets with no index:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[] = “Orwell”;

When you do this, PHP knows that you want to add a new element to the end of the array, and it automatically assigns the next available index — in this case, 4 — to the element.

In fact, you can create an array from scratch simply by creating its elements using the square bracket syntax. The following three examples all produce exactly the same array:

// Creating an array using the array() construct
$authors1 = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
// Creating the same array using [] and numeric indices
$authors2[0] = “Steinbeck”;
$authors2[1] = “Kafka”;
$authors2[2] = “Tolkien”;
$authors2[3] = “Dickens”;
// Creating the same array using the empty [] syntax
$authors3[] = “Steinbeck”;
$authors3[] = “Kafka”;
$authors3[] = “Tolkien”;
$authors3[] = “Dickens”;

However, just as with regular variables, you should make sure your arrays are initialized properly first. In the second and third examples, if the $authors2 or $authors3 array variables already existed and contained other elements, the final arrays might end up containing more than just the four elements you assigned.

This creates an array with no elements (an empty array).

$authors = array();

You can then go ahead and add elements later:

$authors[] = “Steinbeck”;
$authors[] = “Kafka”;
$authors[] = “Tolkien”;
$authors[] = “Dickens”;

You can also add and change elements of associative arrays using square bracket syntax. Here an associative array is populated in two ways: first using the array() construct, and second using the
square bracket syntax:

// Creating an associative array using the array() construct
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );

// Creating the same array using [] syntax
$myBook = array();
$myBook[“title”] = “The Grapes of Wrath”;
$myBook[“author”] = “John Steinbeck”;
$myBook[“pubYear”] = 1939;

Changing elements of associative arrays works in a similar fashion to indexed arrays:

$myBook[“title”] = “East of Eden”;
$myBook[“pubYear”] = 1952;

Outputing Array using print_r():
The print_r() function is a built-in function in PHP and is used to print or display information stored in a variable.
Syntax:
print_r( $variable, $isStore )

·        $variable: This parameter specifies the variable to be printed and is a mandatory parameter.
·        $isStore: This an option parameter. This parameter is of boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the print_r() function will return the output which it is supposed to print.

<?php

# the print_r() function

// string variable
$var1 = "Welcome to IT";
// integer variable
$var2 = 92;

// array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "IT");

// printing the variables
print_r($var1);
echo"\n";
print_r($var2);
echo"\n";
print_r($arr);

?>

<?php

# PHP program to illustrate the print_r()  function when $isStore is set to true

# array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "IT");
                                                                          
# storing output of print_r() function in another variable
$results = print_r($arr, true);

echo $results;

?>

Extracting a Range of Elements with array_slice():
The array_slice() function returns selected parts of an array. In other words the array_slice() is an inbuilt function of PHP and is used to fetch a part of an array by slicing through it, according to the users choice.
Syntax:
array_slice($array, $start_point, $slicing_range, preserve)
$array (mandatory): This parameter refers to the original array, we want to slice.
$start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed. It is mandatory to supply this value. If the value supplied is negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last element of the array.
$slicing _range (optional): This parameter refers to the range or limit point upto which the slicing is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will slice through all the values as mentioned in the starting point right up to the end.
preserve (optional): This parameter can take only two boolean parameters, i.e., either True or False. This will tell the function whether to preserve the keys or reset it. True refers to preserve the keys and false refers to reset the keys. False being the default value.

<?php

// PHP program to illustrate the
// array_slice() function

// Input array
$array = array("Rajesh", "krishna", "Rahul",
                                                                                          "Nandu", "Bhairav");
                                                                                         
// Slice from pos 1 to pos 3                                                                                       
print_r(array_slice($array, 1, 3, true));

?>

count():
The count() function returns the number of elements in an array.
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

Numeric Array:
These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default, array index starts from zero.
Example:
Following is the example showing how to create and access numeric arrays. Here we have used array() function to create array.
 
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
  echo "Value is $value <br />";
}
 
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
 
foreach( $numbers as $value )
{
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays:
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
NOTE: Don't keep associative array inside double quote while printing otherwise it would not return any value.
Example:
<html>
<body>
<?php
# First method to associate create array.
$salaries = array(
                                 "mohammad" => 2000,
                                 "qadir" => 1000,
   "zara" => 500
                                );

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";

# Second method to create array.
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";
?>
</body>
</html>

This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Multidimensional Arrays:
A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
   $marks = array(
                              "mohammad" => array
                              (
                              "physics" => 35,    
                              "maths" => 30,       
                              "chemistry" => 39                
                              ),
                              "qadir" => array
                (
                "physics" => 30,
                "maths" => 32,
                "chemistry" => 29
                ),
                "zara" => array
                (
                "physics" => 31,
                "maths" => 22,
                "chemistry" => 39
                )
                    );
   /* Accessing multi-dimensional array values */
   echo "Marks for mohammad in physics : " ;
   echo $marks['mohammad']['physics'] . "<br />";
   echo "Marks for qadir in maths : ";
   echo $marks['qadir']['maths'] . "<br />";
   echo "Marks for zara in chemistry : " ;
   echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
4.4 Looping with Index based array
foreach is a special kind of looping statement that works only on arrays (and objects). You can use it in two ways. You can either retrieve just the value of each element, or you can retrieve the element’s key and value.
Using foreach to Loop Through Values
The simplest way to use foreach is to retrieve each element’s value, as follows:
foreach ( $array as $value ) {
// (do something with $value here)
}
// (rest of script here)
As you might imagine, the foreach loop continues to iterate until it has retrieved all the values in the array, from the first element to the last. On each pass through the loop, the $value variable gets set to the value of the current element. You can then do whatever you need to do with the value within the loop’s code block. Then, the loop repeats again, getting the next value in the array, and so on.
Example:
<?php
$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
foreach ( $authors as $val ) {
echo $val . "</br>";
}
?>
This code displays:
Steinbeck
Kafka
Tolkien
Dickens
You can use any variable name you like to store the value. Essentially, any variable that you place after the as in the foreach statement gets assigned the current element’s value.
4.5 Looping with associative array using foreach():

To use foreach to retrieve both keys and values, use the following syntax:
foreach ( $array as $key = > $value ) {
// (do something with $key and/or $value here
}
// (rest of script here)
This behaves exactly like the previous foreach construct; the only difference is that the element’s key is also stored in the $key variable. (Again, you can use any variable names you like; they don ’ t have to be
$key and $value .)

<?php
#Declare an associative array
$aso_arr = array(
               "Up"=>"North",
               "Down"=>"South",
               "Left"=>"West",
               "Right"=>"East"
);
#Use foreach loop to traverse each elements of array and display its key and value
foreach($aso_arr as $side=>$direc) {
               echo $side . " => " . $direc . "\n";
}
?>