Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

WEB DESIGNING USING PHP

PHP code is executed on the server.

What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the


web (WordPress)!
It is deep enough to run large social networks!
It is also easy enough to be a beginner's first server side language!

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code is executed on the server, and the result is returned to the
browser as plain HTML
 PHP files have extension ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS,
etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

 A PHP script is executed on the server, and the plain HTML result is
sent back to the browser.

 Basic PHP Syntax


 A PHP script can be placed anywhere in the document.
 A PHP script starts with <?php and ends with ?>:

 <?php

 // PHP code goes here

 ?>

 The default file extension for PHP files is ".php".


 A PHP file normally contains HTML tags, and some PHP scripting code.
 Below, we have an example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text "Hello World!" on
a web page:
 A simple .php file with both HTML code and PHP code:

 <!DOCTYPE html>

 <html>

 <body>

 <h1>My first PHP page</h1>

 <?php

 echo "Hello World!";

 ?>


 </body>

 </html>

 Note: PHP statements end with a semicolon (;)

 PHP Case Sensitivity


 In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions,
and user-defined functions are not case-sensitive.
 In the example below, all three echo statements below are equal and
legal:
 ECHO is the same as echo:

 <!DOCTYPE html>

 <html>

 <body>

 <?php

 ECHO "Hello World!<br>";

 echo "Hello World!<br>";

 EcHo "Hello World!<br>";

 ?>

 </body>

 </html>

 Note: However; all variable names are case-sensitive!


 Look at the example below; only the first statement will display the
value of the $color variable! This is because $color, $COLOR,
and $coLOR are treated as three different variables:

 Example
 $COLOR is not same as $color:

 <!DOCTYPE html>

 <html>
 <body>

 <?php
$color = "red";

 echo "My car is " . $color . "<br>";

 echo "My house is " . $COLOR . "<br>";

 echo "My boat is " . $coLOR . "<br>";

 ?>

 </body>

 </html>

 Try it Yourself »

PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different
variables)

 Variables are "containers" for storing information.

 Creating (Declaring) PHP Variables


 In PHP, a variable starts with the $ sign, followed by the name of the
variable:
 ExampleGet your own PHP Server
 $x = 5;

 $y = "John"

 In the example above, the variable $x will hold the value 5, and the
variable $y will hold the value "John".
 Note: When you assign a text value to a variable, put quotes around
the value.
 Note: Unlike other programming languages, PHP has no command for
declaring a variable. It is created the moment you first assign a value
to it.

Output Variables
The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example
$txt = "W3Schools.com";

echo "I love $txt!";

Output Variables
The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example
$txt = "W3Schools.com";

echo "I love $txt!";

Try it Yourself »

The following example will produce the same output as the example above:
Example
$txt = "W3Schools.com";

echo "I love " . $txt . "!";

Try it Yourself »

The following example will output the sum of two variables:

Example
$x = 5;

$y = 4;

echo $x + $y;

Try it Yourself »

Constants are like variables, except that once they are defined they
cannot be changed or undefined.

PHP Constants
A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name).

Note: Unlike variables, constants are automatically global across the entire
script.

Create a PHP Constant


To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive);

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false. Note: Defining case-insensitive constants
was deprecated in PHP 7.3. PHP 8.0 accepts only false, the value true
will produce a warning.

ExampleGet your own PHP Server


Create a constant with a case-sensitive name:

define("GREETING", "Welcome to W3Schools.com!");

echo GREETING;

Try it Yourself »

Example
Create a constant with a case-insensitive name:

define("GREETING", "Welcome to W3Schools.com!", true);

echo greeting;

PHP const Keyword


You can also create a constant by using the const keyword.

Example
Create a constant with the const keyword:

const MYCAR = "Volvo";

echo MYCAR;

PHP Data Types


Variables can store data of different types, and different data types can do
different things.

PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

Getting the Data Type


You can get the data type of any object by using the var_dump() function.

ExampleGet your own PHP Server


The var_dump() function returns the data type and the value:

$x = 5;

var_dump($x);

Try it Yourself »

PHP String
A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

Example
$x = "Hello world!";

$y = 'Hello world!';
var_dump($x);

echo "<br>";

var_dump($y);

Try it Yourself »

PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.

Rules for integers:

 An integer must have at least one digit


 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in: decimal (base 10), hexadecimal (base
16), octal (base 8), or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function returns


the data type and value:

Example
$x = 5985;

var_dump($x);

Try it Yourself »

ADVERTISEMENT

PHP Float
A float (floating point number) is a number with a decimal point or a number
in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the
data type and value:

Example
$x = 10.365;

var_dump($x);

Try it Yourself »

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

Example
$x = true;

var_dump($x);

Try it Yourself »

Booleans are often used in conditional testing.

You will learn more about conditional testing in the PHP If...Else chapter.

PHP Array
An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function


returns the data type and value:

Example
$cars = array("Volvo","BMW","Toyota");

var_dump($cars);
Try it Yourself »

You will learn a lot more about arrays in later chapters of this tutorial.

PHP Object
Classes and objects are the two main aspects of object-oriented
programming.

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.

Let's assume we have a class named Car that can have properties like model,
color, etc. We can define variables like $model, $color, and so on, to hold the
values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they
inherit all the properties and behaviors from the class, but each object will
have different values for the properties.

If you create a __construct() function, PHP will automatically call this function
when you create an object from a class.

Example
class Car {

public $color;

public $model;

public function __construct($color, $model) {

$this->color = $color;

$this->model = $model;

public function message() {

return "My car is a " . $this->color . " " . $this->model . "!";


}

$myCar = new Car("red", "Volvo");

var_dump($myCar);

Try it Yourself »

Do not worry if you do not understand the PHP Object syntax, you will learn
more about that in the PHP Classes/Objects chapter.

PHP NULL Value


Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a


value of NULL.

Variables can also be emptied by setting the value to NULL:

Example
$x = "Hello world!";

$x = null;

var_dump($x);

Try it Yourself »

Change Data Type


If you assign an integer value to a variable, the type will automatically be an
integer.

If you assign a string to the same variable, the type will change to a string:
Example
$x = 5;

var_dump($x);

$x = "Hello";

var_dump($x);

Try it Yourself »

If you want to change the data type of an existing variable, but not by
changing the value, you can use casting.

Casting allows you to change data type on variables:

Example
$x = 5;

$x = (string) $x;

var_dump($x);

Try it Yourself »

You will learn more about casting in the PHP Casting Chapter.

PHP Resource
The special resource type is not an actual data type. It is the storing of a
reference to functions and resources external to PHP.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators


The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction, multiplication
etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power


PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value
to a variable.

The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.

Assignment Same as... Description

x=y x=y The left operand gets set to the value of the expression on the right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus

ADVERTISEMENT

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or
string):

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they


are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or the
are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal
$y

<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $

<=> Spaceship $x <=> $y Returns an integer less than, equal to, or


greater than zero, depending on if $x is les
than, equal to, or greater than $y.
Introduced in PHP 7.

PHP Increment / Decrement Operators


The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.

Operator Name Example Result


and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

PHP String Operators


PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2


.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1
assignment

PHP Array Operators


The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same


key/value pairs in the same order and of
the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y


PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending
on conditions:

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE

?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.


The value of $x is expr1 if expr1 exists, an
is not NULL.
If expr1 does not exist, or is NULL, the
value of $x is expr2.
Introduced in PHP 7

PHP Exercises
Test Yourself With Exercises
Exercise:
Multiply 10 with 5, and output the result.

echo 10 5;

PHP Loops
Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long
as a certain condition is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition


is true
 do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The following chapters will explain and give examples of each loop type.

The PHP while Loop


The while loop executes a block of code as long as the specified condition is
true.

ExampleGet your own PHP Server


Print $i as long as $i is less than 6:

$i = 1;

while ($i < 6) {

echo $i;

$i++;

If you want the while loop count to 100, but only by each 10, you can
increase the counter by 10 instead 1 in each iteration:

Example
Count to 100 by tens:

$i = 0;

while ($i < 100) {

$i+=10;

echo $i "<br>";
}

The PHP do...while Loop


The do...while loop will always execute the block of code at least once, it will
then check the condition, and repeat the loop while the specified condition is
true.

ExampleGet your own PHP Server


Print $i as long as $i is less than 6:

$i = 1;

do {

echo $i;

$i++;

} while ($i < 6);

The PHP for Loop


The for loop is used when you know how many times the script should run.

Syntax
for (expression1, expression2, expression3) {

// code block

ExampleGet your own PHP Server


Print the numbers from 0 to 10:

for ($x = 0; $x <= 10; $x++) {

echo "The number is: $x <br>";

}
The break Statement
With the break statement we can stop the loop even if the condition is still
true:

Example
Stop the loop when $i is 3:

for ($x = 0; $x <= 10; $x++) {

if ($i == 3) break;

echo "The number is: $x <br>";

The foreach Loop on Arrays


The most common use of the foreach loop, is to loop through the items of an
array.

ExampleGet your own PHP Server


Loop through the items of an indexed array:

$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {

echo "$x <br>";

Break in For loop


The break statement can be used to jump out of a for loop.

ExampleGet your own PHP Server


Jump out of the loop when $x is 4:

for ($x = 0; $x < 10; $x++) {


if ($x == 4) {

break;

echo "The number is: $x <br>";

PHP Continue
❮ PreviousNext ❯

The continue statement can be used to jump out of the current iteration
of a loop, and continue with the next.

Continue in For Loops


The continue statement stops the current iteration in the for loop and
continue with the next.

ExampleGet your own PHP Server


Move to next iteration if $x = 4:

for ($x = 0; $x < 10; $x++) {

if ($x == 4) {

continue;

echo "The number is: $x <br>";

}
PHP Functions
❮ PreviousNext ❯

The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.

PHP Built-in Functions


PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-
in functions.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

 A function is a block of statements that can be used repeatedly in a


program.
 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

Create a Function
A user-defined function declaration starts with the keyword function,
followed by the name of the function:
ExampleGet your own PHP Server
function myMessage() {

echo "Hello world!";

Note: A function name must start with a letter or an underscore. Function


names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

Call a Function
To call the function, just write its name followed by parentheses ():

Example
function myMessage() {

echo "Hello world!";

myMessage();

In our example, we create a function named myMessage().

The opening curly brace { indicates the beginning of the function code, and
the closing curly brace } indicates the end of the function.

The function outputs "Hello world!".

PHP Arrays
❮ PreviousNext ❯
An array stores multiple values in one single variable:

ExampleGet your own PHP Server


$cars = array("Volvo", "BMW", "Toyota");

What is an Array?
An array is a special variable that can hold many values under a single name,
and you can access the values by referring to an index number or name.

PHP Array Types


In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

Array Functions
The real strength of PHP arrays are the built-in array functions, like
the count() function for counting array items:

Example
How many items are in the $cars array:

$cars = array("Volvo", "BMW", "Toyota");

echo count($cars);

PHP Indexed Arrays


In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.
ExampleGet your own PHP Server
Create and display an indexed array:

$cars = array("Volvo", "BMW", "Toyota");

var_dump($cars);

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

ExampleGet your own PHP Server


$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

Create Array
You can create arrays by using the array() function:

ExampleGet your own PHP Server


$cars = array("Volvo", "BMW", "Toyota");

Try it Yourself »

You can also use a shorter syntax by using the [] brackets:

Example
$cars = ["Volvo", "BMW", "Toyota"];

Try it Yourself »

Access Array Item


To access an array item, you can refer to the index number for indexed
arrays, and the key name for associative arrays.
ExampleGet your own PHP Server
Access an item by referring to its index number:

$cars = array("Volvo", "BMW", "Toyota");

echo $cars[2];

Try it Yourself »

Note: The first item has index 0.

To access items from an associative array, use the key name:

Example
Access an item by referring to its key name:

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);

echo $cars["year"];

Try it Yourself »

Double or Single Quotes


You can use both double and single quotes when accessing an array:

Example
echo $cars["model"];

echo $cars['model'];

Try it Yourself »

Excecute a Function Item


Array items can be of any data type, including function.
To execute such a function, use the index number followed by
parentheses ():

Example
Execute a function item:

function myFunction() {

echo "I come from a function!";

$myArr = array("Volvo", 15, myFunction);

$myArr[2]();

The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a
submit button:

ExampleGet your own PHP Server


<html>
<body>

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


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Run Example »
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form
data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

Welcome John
Your email address is john.doe@example.com

The same result could also be achieved using the HTTP GET method:

Example
<html>
<body>

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


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Run Example »

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where keys
are the names of the form controls and values are the input data from the
user.

Both GET and POST are treated as $_GET and $_POST. These are
superglobals, which means that they are always accessible, regardless of
scope - and you can access them from any function, class or file without
having to do anything special.

$_GET is an array of variables passed to the current script via the URL
parameters.

$_POST is an array of variables passed to the current script via the HTTP
POST method.

When to use GET?


Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL). GET also
has limits on the amount of information to send. The limitation is about 2000
characters. However, because the variables are displayed in the URL, it is
possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive
information!

When to use POST?


Information sent from a form with the POST method is invisible to
others (all names/values are embedded within the body of the HTTP
request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-
part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.

Developers prefer POST for sending form data.

PHP Complete Form Example


❮ PreviousNext ❯

This chapter shows how to keep the values in the input fields when the
user hits the submit button.

PHP - Keep The Values in The Form


To show the values in the input fields after the user hits the submit button,
we add a little PHP script inside the value attribute of the following input
fields: name, email, and website. In the comment textarea field, we put the
script between the <textarea> and </textarea> tags. The little script
outputs the value of the $name, $email, $website, and $comment variables.

Then, we also need to show which radio button that was checked. For this,
we must manipulate the checked attribute (not the value attribute for radio
buttons):

Name: <input type="text" name="name" value="<?php echo $name;?>">

E-mail: <input type="text" name="email" value="<?php echo $email;?>">

Website: <input type="text" name="website" value="<?php echo $website;?


>">

Comment: <textarea name="comment" rows="5" cols="40"><?php echo $commen


t;?></textarea>

Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other

ADVERTISEMENT

PHP - Complete Form Example


Here is the complete code for the PHP Form Validation Example:

ExampleGet your own PHP Server


Run Example »

❮ PreviousNext ❯

PHP What is OOP?


OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that


perform operations on the data, while object-oriented programming is about
creating objects that contain both data and functions.

Object-oriented programming has several advantages over procedural


programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less
code and shorter development time

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the
repetition of code. You should extract out the codes that are common for the
application, and place them at a single place and reuse them instead of
repeating it.

PHP - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented
programming.

Look at the following illustration to see the difference between class and
objects:

class
Fruit

objects
Apple

Banana

Mango

Another example:

class
Car

objects
Volvo

Audi
Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.

PHP Namespaces
❮ PreviousNext ❯

PHP Namespaces
Namespaces are qualifiers that solve two different problems:

1. They allow for better organization by grouping classes that work


together to perform a task
2. They allow the same name to be used for more than one class

For example, you may have a set of classes which describe an HTML table,
such as Table, Row and Cell while also having another set of classes to
describe furniture, such as Table, Chair and Bed. Namespaces can be used to
organize the classes into two different groups while also preventing the two
classes Table and Table from being mixed up.

Declaring a Namespace
Namespaces are declared at the beginning of a file using
the namespace keyword:

SyntaxGet your own PHP Server


Declare a namespace called Html:
<?php
namespace Html;
?>

PHP OOP - Classes and


Objects
❮ PreviousNext ❯

A class is a template for objects, and an object is an instance of class.

OOP Case
Let's assume we have a class named Fruit. A Fruit can have properties like
name, color, weight, etc. We can define variables like $name, $color, and
$weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all
the properties and behaviors from the class, but each object will have
different values for the properties.

Define a Class
A class is defined by using the class keyword, followed by the name of the
class and a pair of curly braces ({}). All its properties and methods go inside
the braces:

SyntaxGet your own PHP Server


<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Fruit consisting of two properties ($name
and $color) and two methods set_name() and get_name() for setting and
getting the $name property:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

Note: In a class, variables are called properties and functions are called
methods!

PHP - The __construct Function


A constructor allows you to initialize an object's properties upon creation of
the object.

If you create a __construct() function, PHP will automatically call this function
when you create an object from a class.

Notice that the construct function starts with two underscores (__)!

We see in the example below, that using a constructor saves us from calling
the set_name() method which reduces the amount of code:

ExampleGet your own PHP Server


<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>

Try it Yourself »

Another example:

Example
<?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}

$apple = new Fruit("Apple", "red");


echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

PHP - The __destruct Function


A destructor is called when the object is destructed or the script is stopped or
exited.

If you create a __destruct() function, PHP will automatically call this function
at the end of the script.

Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called
when you create an object from a class, and a __destruct() function that is
automatically called at the end of the script:

ExampleGet your own PHP Server


<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>

Try it Yourself »

Another example:

Example
<?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

$apple = new Fruit("Apple", "red");


?>

Try it Yourself »
Tip: As constructors and destructors helps reducing the amount of code,
they are very useful!

PHP - What is an Iterable?


An iterable is any value which can be looped through with a foreach() loop.

The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a
data type for function arguments and function return values.

PHP - Using Iterables


The iterable keyword can be used as a data type of a function argument or
as the return type of a function:

ExampleGet your own PHP Server


Use an iterable function argument:

<?php
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}

$arr = ["a", "b", "c"];


printIterable($arr);
?>

Try it Yourself »

PHP - What is Inheritance?


Inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties and
methods from the parent class. In addition, it can have its own properties
and methods.
An inherited class is defined by using the extends keyword.

Let's look at an example:

ExampleGet your own PHP Server


<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

PHP - What are Interfaces?


Interfaces allow you to specify what methods a class should implement.

Interfaces make it easy to use a variety of different classes in the same way.
When one or more classes use the same interface, it is referred to as
"polymorphism".

Interfaces are declared with the interface keyword:

SyntaxGet your own PHP Server


<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
public function someMethod3() : string;
}
?>

PHP - Interfaces vs. Abstract Classes


Interface are similar to abstract classes. The difference between interfaces
and abstract classes are:

 Interfaces cannot have properties, while abstract classes can


 All interface methods must be public, while abstract class methods is
public or protected
 All methods in an interface are abstract, so they cannot be
implemented in code and the abstract keyword is not necessary
 Classes can implement an interface while inheriting from another class
at the same time

PHP - Using Interfaces


To implement an interface, a class must use the implements keyword.

A class that implements an interface must implement all of the interface's


methods.

Example
<?php
interface Animal {
public function makeSound();
}

class Cat implements Animal {


public function makeSound() {
echo "Meow";
}
}

$animal = new Cat();


$animal->makeSound();
?>

Try it Yourself »
From the example above, let's say that we would like to write software which
manages a group of animals. There are actions that all of the animals can do,
but each animal does it in its own way.

Using interfaces, we can write some code which can work for all of the
animals even if each animal behaves differently:

Example
<?php
// Interface definition
interface Animal {
public function makeSound();
}

// Class definitions
class Cat implements Animal {
public function makeSound() {
echo " Meow ";
}
}

class Dog implements Animal {


public function makeSound() {
echo " Bark ";
}
}

class Mouse implements Animal {


public function makeSound() {
echo " Squeak ";
}
}

// Create a list of animals


$cat = new Cat();
$dog = new Dog();
$mouse = new Mouse();
$animals = array($cat, $dog, $mouse);

// Tell the animals to make a sound


foreach($animals as $animal) {
$animal->makeSound();
}
?>

Try it Yourself »
Example Explained
Cat, Dog and Mouse are all classes that implement the Animal interface,
which means that all of them are able to make a sound using
the makeSound() method. Because of this, we can loop through all of the
animals and tell them to make a sound even if we don't know what type of
animal each one is.

Since the interface does not tell the classes how to implement the method,
each animal can make a sound in its own way.

PHP Exception Handling

Exceptions are used to change the normal flow of a script if a specified


error occurs.

What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.

Exception handling is used to change the normal flow of the code execution if
a specified error (exceptional) condition occurs. This condition is called an
exception.

This is what normally happens when an exception is triggered:

 The current code state is saved


 The code execution will switch to a predefined (custom) exception
handler function
 Depending on the situation, the handler may then resume the
execution from the saved code state, terminate the script execution or
continue the script from a different location in the code

We will show different error handling methods:

 Basic use of Exceptions


 Creating a custom exception handler
 Multiple exceptions
 Re-throwing an exception
 Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not
be used to jump to another place in the code at a specified point.

Basic Use of Exceptions


When an exception is thrown, the code following it will not be executed, and
PHP will try to find the matching "catch" block.

If an exception is not caught, a fatal error will be issued with an "Uncaught


Exception" message.

Lets try to throw an exception without catching it:

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception 'Exception'


with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch


To avoid the error from the example above, we need to create the proper
code to handle an exception.

Proper exception code should include:


1. try - A function using an exception should be in a "try" block. If the
exception does not trigger, the code will continue as normal. However
if the exception triggers, an exception is "thrown"
2. throw - This is how you trigger an exception. Each "throw" must have
at least one "catch"
3. catch - A "catch" block retrieves an exception and creates an object
containing the exception information

Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception in a "try" block


try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like this:

Message: Value must be 1 or below

Example explained:
The code above throws an exception and catches it:

1. The checkNum() function is created. It checks if a number is greater


than 1. If it is, an exception is thrown
2. The checkNum() function is called in a "try" block
3. The exception within the checkNum() function is thrown
4. The "catch" block retrieves the exception and creates an object ($e)
containing the exception information
5. The error message from the exception is echoed by calling $e-
>getMessage() from the exception object

However, one way to get around the "every throw must have a catch" rule is
to set a top level exception handler to handle errors that slip through.

PHP Create File - fopen()


The fopen() function is also used to create a file. Maybe a little confusing, but
in PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the
file is opened for writing (w) or appending (a).

The example below creates a new file called "testfile.txt". The file will be
created in the same directory where the PHP code resides:

ExampleGet your own PHP Server


$myfile = fopen("testfile.txt", "w")

PHP File Upload


❮ PreviousNext ❯

With PHP, it is easy to upload files to the server.

However, with ease comes danger, so always be careful when allowing file
uploads!

Configure The "php.ini" File


First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With PHP, you
can both create and retrieve cookie values.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

A session is a way to store information (in variables) to be used across


multiple pages.

Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?


When you work with an application, you open it, do some changes, and then
you close it. This is much like a Session. The computer knows who you are.
It knows when you start the application and when you end. But on the
internet there is one problem: the web server does not know who you are or
what you do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used


across multiple pages (e.g. username, favorite color, etc). By default, session
variables last until the user closes the browser.

So; Session variables hold information about one single user, and are
available to all pages in one application.

Tip: If you need a permanent storage, you may want to store the data in
a database.

Another way to show all the session variable values for a user session is to
run the following code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

Run example »

What is RDBMS?
RDBMS stands for Relational Database Management System.

RDBMS is a program used to maintain a relational database.

RDBMS is the basis for all modern database systems such as MySQL,
Microsoft SQL Server, Oracle, and Microsoft Access.

RDBMS uses SQL queries to access the data in the database.

What is a Database Table?


A table is a collection of related data entries, and it consists of columns and
rows.

A column holds specific information about every record in the table.

A record (or row) is each individual entry that exists in a table.

Look at a selection from the Northwind "Customers" table:

CustomerID CustomerName ContactName Address City PostalC


1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023


D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 2


Berglund

The columns in the "Customers" table above are: CustomerID,


CustomerName, ContactName, Address, City, PostalCode and Country. The
table has 5 records (rows).

ADVERTISEMENT

What is a Relational Database?


A relational database defines database relationships in the form of tables.
The tables are related to each other - based on data common to each.

Look at the following three tables "Customers", "Orders", and "Shippers"


from the Northwind database:
Customers Table

CustomerID CustomerName ContactName Address City PostalC

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023


D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 2


Berglund

The relationship between the "Customers" table and the "Orders" table is the
CustomerID column:

Orders Table

OrderID CustomerID EmployeeID OrderDate Shipp

10278 5 8 1996-08-12 2
10280 5 2 1996-08-14 1

10308 2 7 1996-09-18 3

10355 4 6 1996-11-15 1

10365 3 3 1996-11-27 2

10383 4 8 1996-12-16 3

10384 5 3 1996-12-16 3

The relationship between the "Orders" table and the "Shippers" table is the
ShipperID column:

Shippers Table

ShipperID ShipperName Phone

1 Speedy Express (503) 555-9831

2 United Package (503) 555-3199

3 Federal Shipping (503) 555-9931


MySQL Joining Tables
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName C

1 Alfreds Futterkiste Maria Anders G

2 Ana Trujillo Emparedados y helados Ana Trujillo M

3 Antonio Moreno Taquería Antonio Moreno M


Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two
tables above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER
JOIN), that selects records that have matching values in both tables:

ExampleGet your own SQL Server


SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Try it Yourself »

and it will produce something like this:

OrderID CustomerName O

10308 Ana Trujillo Emparedados y helados 9

10365 Antonio Moreno Taquería 1

10383 Around the Horn 1

10355 Around the Horn 1

10278 Berglunds snabbköp 8

ADVERTISEMENT
Supported Types of Joins in MySQL
 INNER JOIN: Returns records that have matching values in both tables
 LEFT JOIN: Returns all records from the left table, and the matched
records from the right table
 RIGHT JOIN: Returns all records from the right table, and the matched
records from the left table
 CROSS JOIN: Returns all records from both tables

Test Yourself With Exercises


Exercise:
Insert the missing parts in the JOIN clause to join the two
tables Orders and Customers, using the CustomerID field in both tables as the
relationship between the two tables.

SELECT *
FROM Orders
LEFT JOIN Customers
=;

Submit Answer »

Start the Exercise


What is SQL?
SQL is the standard language for dealing with Relational Databases.

SQL is used to insert, search, update, and delete database records.

How to Use SQL


The following SQL statement selects all the records in the "Customers" table:

ExampleGet your own SQL Server


SELECT * FROM Customers;

Try it Yourself »

Keep in Mind That...


 SQL keywords are NOT case sensitive: select is the same as SELECT

In this tutorial we will write all SQL keywords in upper-case.

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL
statement.

Semicolon is the standard way to separate each SQL statement in database


systems that allow more than one SQL statement to be executed in the same
call to the server.

In this tutorial, we will use semicolon at the end of each SQL statement.
Some of The Most Important SQL
Commands
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

SVG Advantages
Advantages of using SVG over other image formats (like JPEG and GIF) are:

 SVG images can be created and edited with any text editor
 SVG images can be searched, indexed, scripted, and compressed
 SVG images are scalable
 SVG images can be printed with high quality at any resolution
 SVG images are zoomable
 SVG graphics do NOT lose any quality if they are zoomed or resized
 SVG is an open standard
 SVG files are pure XML

How does it Work?


SVG has elements and attributes for rectangles, circles, ellipses, lines,
polygons, curves, and more.

SVG also supports filter and blur effects, gradients, rotations, animations,
interactivity with JavaScript, and more.

A simple SVG document consists of the <svg> root element and several
basic shape elements that will build a graphic together.
Creating SVG Images
SVG images can be created with any text editor, or with a drawing program,
like Inkscape.

For you to learn the concept and basics of SVG, this tutorial will just use
plain text to teach you SVG.

The next page shows how to embed an SVG image directly into an HTML
page!

<html>
<body>

<h1>My first SVG</h1>

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">


<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fil
l="yellow" />
</svg>

</body>
</html>

PHP MySQL Database


❮ PreviousNext ❯

With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of


related data, and it consists of columns and rows.

Databases are useful for storing information categorically. A company may


have a database with the following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL Database System


 PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform)

Database Queries
A query is a question or a request.

We can query a database for specific information and have a recordset


returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the
"Employees" table.

You might also like