0% found this document useful (0 votes)
33 views

PHP Note Full

PHP is a widely used open source scripting language used on servers to create dynamic web page content. PHP code is embedded into HTML files and executed on the server to produce HTML that is then sent to the browser. PHP can be used to collect form data, connect to databases, generate images and files, and more. It runs on many platforms and is compatible with popular servers like Apache. PHP uses .php files and code is placed between <?php ?> tags. Variables start with $ and do not require data type declaration. PHP has global, local, and static variable scopes.

Uploaded by

anwar.negash2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

PHP Note Full

PHP is a widely used open source scripting language used on servers to create dynamic web page content. PHP code is embedded into HTML files and executed on the server to produce HTML that is then sent to the browser. PHP can be used to collect form data, connect to databases, generate images and files, and more. It runs on many platforms and is compatible with popular servers like Apache. PHP uses .php files and code is placed between <?php ?> tags. Variables start with $ and do not require data type declaration. PHP has global, local, and static variable scopes.

Uploaded by

anwar.negash2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Source: www.w3schools.

com

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 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.

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 the largest social network (Facebook)! 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 are 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

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?

 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.
 PHP is easy to learn and runs efficiently on the server side

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:

Example

<html>
<body>
<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

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

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>

PHP Case Sensitivity

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>

Creating (Declaring) PHP Variables

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.

Think of variables as containers for storing data.

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).

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)

Remember that PHP variable names are case-sensitive!

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 . "!";
?>

The following example will output the sum of two variables:

Example

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

5
Source: www.w3schools.com

PHP is a Loosely Typed Language

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.

PHP Variables Scope


In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of
the script where the variable can be referenced/used.

PHP has three different variable scopes:

 local
 global
 static

Global and Local Scope

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();

echo "<p>Variable x outside function is: $x</p>";


?>

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();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

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.

PHP The global Keyword


The global keyword is used to access a global variable from within a function. To do this, use the
global keyword before the variables (inside the function):

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.

The example above can be rewritten like this:

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.

PHP echo and print Statements


echo and print are more or less the same. They are both used to output data to the screen.

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.

PHP String Functions


In this chapter we will look at some commonly used functions to manipulate strings.

8
Source: www.w3schools.com

Get the Length of a String

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
?>

The output of the code above will be: 12.

Count the Number of Words in a String


The PHP str_word_count() function counts the number of words in a string:

Example

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

The output of the code above will be: 2.

Reverse a String
The PHP strrev() function reverses a string:

Example

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

The output of the code above will be: !dlrow olleH.

Search for a Specific Text Within a String

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 output of the code above will be: 6.

Tip: The first character position in a string is 0 (not 1).

Replace Text within a String

The PHP str_replace() function replaces some characters with some other characters in a string.

The example below replaces the text "world" with "Dolly":

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

PHP Arithmetic 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

Operator Name Example Result

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

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

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

+ Addition $x + $y Sum 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

PHP Comparison Operators

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

11
Source: www.w3schools.com

Operator Name Example Result

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

Returns true if $x is equal to $y, and they are of the


=== Identical $x === $y
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

Returns true if $x is not equal to $y, or they are not of


!== Not identical $x !== $y
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
>= $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

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 Name 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.

12
Source: www.w3schools.com

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 assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Conditional Statements

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:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif....else statement - executes different codes for more than two conditions

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");

if ($t < "20") {


echo "Have a good day!";
}
?>

The if...else Statement


The if....else statement executes some code if a condition is true and another code if that
condition is false.

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");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

14
Source: www.w3schools.com

The if...elseif....else Statement


The if....elseif...else statement executes different codes for more than two conditions.

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");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

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

 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 PHP while Loop

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

Syntax

while (condition is true) {


code to be executed;
}

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 PHP do...while Loop

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);
?>

The PHP for Loop


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

Syntax

17
Source: www.w3schools.com

for (init counter; test counter; increment counter) {


code to be executed;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

PHP fore ach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax

foreach ($array as $value) {


code to be executed;
}

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");

foreach ($colors as $value) {


echo "$value <br>";

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!

Function names are NOT case-sensitive.

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!";
}

writeMsg(); // call the function


?>

PHP Function Arguments

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");
?>

PHP Default Argument Value

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);
?>

PHP - A Simple HTML Form

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

Example

<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>

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 [email protected]

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

21
Source: www.w3schools.com

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>

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>

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 vs. POST


Both GET and POST are treated as $_GET and $_POST. These are super global, 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.

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!

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.

PHP include and require Statements

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.

How does it work? How does it know it's me?

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.

Destroy a PHP Session


To remove all global session variables and destroy the session, use session_unset() and
session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

Note:

session_unset() is not used to destroy session, but to remove all assigned session variables.

PHP MySQL Database

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

 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

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):

SELECT LastName FROM Employees

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

$conn = mysqli_connect("localhost", "root", "","dbname");

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Description

The above connection is for MySQLi (improved).

Mysqli_connect is used to connect with the server

Localhost is the name of server

27
Source: www.w3schools.com

Root is default username of your server

"" (which is empty) is the password of the server

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 SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

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.

The following examples add a new record to the "Student" table:

Example (for MySQLi)

<?php
$conn = mysqli_connect("localhost", "root", "","dbreg");

if (!$conn) { // Check connection

die("Connection failed: " . mysqli_connect_error());

28
Source: www.w3schools.com

$sql = "INSERT INTO Student (id,firstname, lastname, age)


VALUES ('1123','John', 'Doe', 21)";

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:

SELECT column_name(s) FROM table_name

Or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

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);
?>

Code lines to explain from the example above:

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.

You can also put the result in an HTML table:

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:

DELETE FROM table_name


WHERE some_column = some_value

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!

Let's look at the "Student" table:

id firstname lastname age

1122 John Doe 21

2213 Mary Moe 20

1321 Julie Dooley 21

The following examples delete the record with id=1321 in the "Student" table:

Example (MySQLi Procedural)

<?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:

id firstname lastname age

1122 John Doe 21

2213 Mary Moe 20

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!

Let's look at the "Student" table:

id firstname lastname age

1122 John Doe 21

2213 Mary Moe 20

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

$sql = "UPDATE Student SET lastname='Moe' WHERE id=1122";

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:

id firstname lastname age

1122 John Moe 21

2213 Mary Moe 20

Limit Data Selections from a MySQL Database

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:

$sql = "SELECT * FROM Orders LIMIT 30";

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)":

$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";

You could also use a shorter syntax to achieve the same result:

$sql = "SELECT * FROM Orders LIMIT 15, 10";

Notice that the numbers are reversed when you use a comma.

33

You might also like