PHP Note Full
PHP Note Full
com
What is PHP?
PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web
pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's
ASP.
It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!
It is deep enough to run the largest social network (Facebook)! It is also easy enough to be a
beginner's first server side language!
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
1
Source: www.w3schools.com
With PHP you are not limited to output HTML. You can output images, PDF files, and even
Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
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:
Example
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Comments in PHP
2
Source: www.w3schools.com
A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
Example
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
In PHP, all 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
legal (and equal):
Example
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
3
Source: www.w3schools.com
However; all variable names are case-sensitive. In 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
<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>
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!,
the variable $x will hold the value 5, and the variable $y will hold the value 10.5.
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.
4
Source: www.w3schools.com
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)
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
<?php
$txt = "metitech.com";
echo "I love $txt!";
?>
The following example will produce the same output as the example above:
Example
<?php
$txt = "metitech.com";
echo "I love " . $txt . "!";
?>
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
5
Source: www.w3schools.com
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value. In other
languages such as C, C++, and Java, the programmer must declare the name and type of the
variable before using it.
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Example
<?php
function myTest() {
6
Source: www.w3schools.com
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.
Example
<?php
$x = 5;
$y = 10;
7
Source: www.w3schools.com
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
The static Keyword
Normally, when a function is completed/ executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this,
use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
8
Source: www.w3schools.com
The PHP strlen() function returns the length of a string. The example below returns the length of
the string "Hello world!":
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE. The example below searches for the text "world" in the string "Hello world!":
9
Source: www.w3schools.com
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The PHP str_replace() function replaces some characters with some other characters in a string.
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs
Hello Dolly!
?>
The output of the code above will be: Hello Dolly!
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
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
10
Source: www.w3schools.com
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
The PHP comparison operators are used to compare two values (number or string):
11
Source: www.w3schools.com
Greater than or
>= $x >= $y Returns true if $x is greater than or equal to $y
equal to
Less than or
<= $x <= $y Returns true if $x is less than or equal to $y
equal to
The PHP increment operators are used to increment a variable's value. The PHP decrement
operators are used to decrement a variable's value.
12
Source: www.w3schools.com
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this. In PHP we have the following
conditional statements:
The if Statement
The if statement executes some code if one condition is true.
Syntax
13
Source: www.w3schools.com
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
Example
<?php
$t = date("H");
14
Source: www.w3schools.com
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":
Example
<?php
$t = date("H");
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this. In PHP, we have the following looping statements:
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
15
Source: www.w3schools.com
The while loop executes a block of code as long as the specified condition is true.
Syntax
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to
run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop
runs ($x++):
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
16
Source: www.w3schools.com
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:
Example
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Syntax
17
Source: www.w3schools.com
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element. The following example
demonstrates a loop that will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
18
Source: www.w3schools.com
}
?>
Function in PHP
A user defined function declaration starts with the word "function":
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named "writeMsg()". 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!". To call the function, just write its name:
Example
<?php
function writeMsg() {
echo "Hello world!";
}
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
19
Source: www.w3schools.com
The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
20
Source: www.w3schools.com
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
The example below displays a simple HTML form with two input fields and a submit button:
Example
<html>
<body>
</body>
</html>
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 [email protected]
The same result could also be achieved using the HTTP GET method:
21
Source: www.w3schools.com
Example
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.
$_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.
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.
22
Source: www.w3schools.com
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!
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.
The include (or require) statement takes all the text/code/markup that exists in the specified file
and copies it into the file that uses the include statement. Including files is very useful when you
want to include the same PHP, HTML, or text on multiple pages of a website.
It is possible to insert the content of one PHP file into another PHP file (before the server
executes it), with the include or require statement. The include and require statements are
identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is
missing, use the include statement. Otherwise, in case of Frame Work, CMS, or a complex PHP
application coding, always use the require statement to include a key file to the flow of
execution. This will help avoid compromising your application's security and integrity, just in-
case one key file is accidentally missing.
23
Source: www.w3schools.com
Including files saves a lot of work. This means that you can create a standard header, footer, or
menu file for all your web pages. Then, when the header needs to be updated, you can only
update the header include file.
Syntax
include 'filename';
or
require 'filename';
The require statement is also used to include a file into the PHP code. However, there is one big
difference between include and require; when a file is included with the include statement and
PHP cannot find it, the script will continue to execute. If we do the same example using the
require statement, the echo statement will not be executed because the script execution dies after
the require statement returned a fatal error.
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. 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 user's computer.
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
24
Source: www.w3schools.com
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any
HTML tags.
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()). Also notice
that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Favorite color is green.
Favorite animal is cat.
The output shows us that session variable can be accessed on another page.
25
Source: www.w3schools.com
Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans
the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new
session.
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
Note:
session_unset() is not used to destroy session, but to remove all assigned session variables.
With PHP, you can connect to and manipulate databases. MySQL is the most popular database
system used with PHP.
What is MySQL?
26
Source: www.w3schools.com
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.
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):
The query above selects all the data in the "LastName" column from the "Employees" table.
The following table shows us how to connect to the server "localhost" using php code.
Example
<?php
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Description
27
Source: www.w3schools.com
Dbname is the name of database that is found in the server and i am to use
After you connect to your server and finalize activities, it is recommended to close the
connection. To do that use the following code:
mysqli_close($conn);
Insert Data
After a database and a table have been created, we can start adding data in them. Here are some
syntax rules to follow:
The INSERT INTO statement is used to add new records to a MySQL table:
Let us assume that we have a database with the name "dbreg". And table named "Student" with
four columns: "id", "firstname", "lastname" and "age". Now, let us fill the table with data.
<?php
$conn = mysqli_connect("localhost", "root", "","dbreg");
28
Source: www.w3schools.com
if (mysqli_query($conn, $sql)) {
echo "<script>alert('New record created successfully');</script>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Select Data
The SELECT statement is used to select data from one or more tables:
The following example selects the id, firstname and lastname columns from the Student table
and displays it on the page:
Example (MySQLi)
<?php
$conn = mysqli_connect("localhost", "root", "","dbreg");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM Student";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
29
Source: www.w3schools.com
mysqli_close($conn);
?>
First, we set up an SQL query that selects the id, firstname and lastname columns from the
Student table. The next line of code runs the query and puts the resulting data into a variable
called $result. Dont foraget that mysqli_query is used to process the query written.
The function fetch_assoc() puts all the results into an associative array that we can loop through.
The while() loop loops through the result set and outputs the data from the id, firstname and
lastname columns.
Example
<?php
$conn = mysqli_connect("localhost", "root", "","dbreg");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM Student";
$result = mysqli_query($conn, $sql);
echo "<table><tr><th>ID</th><th>Name</th></tr>";
while($row = mysqli_fetch_assoc($result))
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]."
".$row["lastname"]."</td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
30
Source: www.w3schools.com
Delete Data
The DELETE statement is used to delete records from a table:
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
The following examples delete the record with id=1321 in the "Student" table:
<?php
$conn = mysqli_connect("localhost", "root", "","dbreg");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=1321";
if (mysqli_query($conn, $sql))
echo "<script>alert('Record deleted successfully');</script>";
else
echo "Error deleting record: " . mysqli_error($conn);
mysqli_close($conn);
?>
31
Source: www.w3schools.com
After the record is deleted, the table will look like this:
Update Data
The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
The following examples update the record with id=1122 in the "Student" table:
Example (MySQLi)
<?php
$conn = mysqli_connect("localhost", "root", "","dbreg");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
32
Source: www.w3schools.com
if (mysqli_query($conn, $sql))
echo "<script>alert('Record updated successfully');</script>";
else
echo "Error updating record: " . mysqli_error($conn);
mysqli_close($conn);
?>
After the record is updated, the table will look like this:
MySQL provides a LIMIT clause that is used to specify the number of records to return. The
LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful
on large tables. Returning a large number of records can impact on performance. Assume we
wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query
would then look like this:
When the SQL query above is run, it will return the first 30 records. What if we want to select
records 16 - 25 (inclusive)? Mysql also provides a way to handle this: by using OFFSET. The
SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":
You could also use a shorter syntax to achieve the same result:
Notice that the numbers are reversed when you use a comma.
33