PHP Notes
PHP Notes
PHP Notes
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
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.
<?php
?>
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Example
$COLOR is not same as $color:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
?>
</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).
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)
$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";
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";
Try it Yourself »
The following example will produce the same output as the example above:
Example
$txt = "W3Schools.com";
Try it Yourself »
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.
Parameters:
echo GREETING;
Try it Yourself »
Example
Create a constant with a case-insensitive name:
echo greeting;
Example
Create a constant with the const keyword:
echo MYCAR;
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
$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.
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 »
You will learn more about conditional testing in the PHP If...Else chapter.
PHP Array
An array stores multiple values in one single variable.
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.
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;
$this->color = $color;
$this->model = $model;
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.
A variable of data type NULL is a variable that has no value assigned to it.
Example
$x = "Hello world!";
$x = null;
var_dump($x);
Try it Yourself »
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.
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.
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
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.
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
!== Not identical $x !== $y Returns true if $x is not equal to $y, or the
are not of the same type
>= 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 $
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.
The following chapters will explain and give examples of each loop type.
$i = 1;
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;
$i+=10;
echo $i "<br>";
}
$i = 1;
do {
echo $i;
$i++;
Syntax
for (expression1, expression2, expression3) {
// code block
}
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:
if ($i == 3) break;
break;
PHP Continue
❮ PreviousNext ❯
The continue statement can be used to jump out of the current iteration
of a loop, and continue with the next.
if ($x == 4) {
continue;
}
PHP Functions
❮ PreviousNext ❯
PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.
Please check out our PHP reference for a complete overview of the PHP built-
in functions.
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() {
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() {
myMessage();
The opening curly brace { indicates the beginning of the function code, and
the closing curly brace } indicates the end of the function.
PHP Arrays
❮ PreviousNext ❯
An array stores multiple values in one single variable:
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.
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:
echo count($cars);
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:
var_dump($cars);
var_dump($car);
Create Array
You can create arrays by using the array() function:
Try it Yourself »
Example
$cars = ["Volvo", "BMW", "Toyota"];
Try it Yourself »
echo $cars[2];
Try it Yourself »
Example
Access an item by referring to its key name:
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];
Try it Yourself »
Example
echo $cars["model"];
echo $cars['model'];
Try it Yourself »
Example
Execute a function item:
function myFunction() {
$myArr[2]();
The PHP superglobals $_GET and $_POST are used to collect form-data.
</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>
</body>
</html>
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>
</body>
</html>
Run Example »
<html>
<body>
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.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
This chapter shows how to keep the values in the input fields when the
user hits the submit button.
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):
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
❮ PreviousNext ❯
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.
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
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:
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:
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:
<?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!
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:
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
Try it Yourself »
Another example:
Example
<?php
class Fruit {
public $name;
public $color;
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:
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
Try it Yourself »
Another example:
Example
<?php
class Fruit {
public $name;
public $color;
Try it Yourself »
Tip: As constructors and destructors helps reducing the amount of code,
they are very useful!
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
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
Try it Yourself »
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.
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".
Example
<?php
interface Animal {
public function 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 ";
}
}
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.
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.
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.
<?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);
?>
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Example explained:
The code above throws an exception and catches it:
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.
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:
However, with ease comes danger, so always be careful when allowing 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.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
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 the basis for all modern database systems such as MySQL,
Microsoft SQL Server, Oracle, and Microsoft Access.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1
ADVERTISEMENT
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1
The relationship between the "Customers" table and the "Orders" table is the
CustomerID column:
Orders Table
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
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Then, we can create the following SQL statement (that contains an INNER
JOIN), that selects records that have matching values in both tables:
Try it Yourself »
OrderID CustomerName O
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
SELECT *
FROM Orders
LEFT JOIN Customers
=;
Submit Answer »
Try it Yourself »
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
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>
</body>
</html>
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
Employees
Products
Customers
Orders
Database Queries
A query is a question or a request.
The query above selects all the data in the "LastName" column from the
"Employees" table.