0% found this document useful (0 votes)
11 views22 pages

PHP Tutorial Advanced Level IT

Advanced Level Students in Sri Lanka

Uploaded by

ISURU SANJEEWA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views22 pages

PHP Tutorial Advanced Level IT

Advanced Level Students in Sri Lanka

Uploaded by

ISURU SANJEEWA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

What is PHP?

PHP is an open-source general purpose scripting language, widely used for website
development. It is developed by Rasmus Lerdorf. PHP stands for a recursive acronym PHP:
Hypertext Preprocessor.
PHP is a server-side scripting language that is embedded in HTML. PHP is a cross-platform
language, capable of running on all major operating system platforms and with most of the web
server programs such as Apache, IIS, lighttpd and nginx.

Hello World Using PHP


Just to give you a little excitement about PHP, I'm going to give you a small conventional PHP
Hello World program.

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

A PHP script may contain a mix of HTML and PHP code.

<html>
<body>
<h1>My PHP Website</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

The "Hello World" message will be rendered as a plain text. However, you can put HTML
tags inside the "Hello World" string. The browser will interpret the tags accordingly.

PHP – Comments
A comment in any computer program (such as a PHP program) is a certain explanatory text
that is ignored by the language compiler/interpreter. Its purpose is to help the user understand
the logic used in the program algorithm.
There are two commenting formats in PHP −
 Single-line Comments
 Multi-line Comments

Page | 1
Single-line Comments
They are generally used for short explanations or notes relevant to the local code. PHP uses
two notations for inserting a single-line comment in a program.
A line in PHP code starting with the "#" symbol is treated as a single-line comment.

<?php
# Single line comment starting with # symbol
echo 'Hello World';
?>

PHP also supports C style of single-line comments with "//" symbol. A line starting with
double oblique symbol is treated as a comment.

<?php
// Single line comment starting with // symbol
echo 'Hello World';
?>

Multi-line Comments
Multi-line comments are generally used to provide pseudocode algorithms and more detailed
explanations when necessary.
The multiline style of commenting is the same as in C. One or more lines embedded inside
the "/*" and "*/" symbols are treated as a comment.

<?php
/* This is a multiline comment example
program to add two numbers
Variables used - $x for first number,
$y for second number */
?>

Variables
 A variable in PHP is a named memory location that holds data belonging to one of the
data types.
 PHP uses the convention of prefixing a dollar sign ($) to the name of a variable.

Page | 2
 Variable names in PHP are case-sensitive.
 Variable names follow the same rules as other labels in PHP. A valid variable name
starts with a letter or underscore, followed by any number of letters, numbers, or
underscores.
 As per the naming convention, "$name", "$rate_of_int", "$Age", "$mark1" are
examples of valid variable names in PHP.
 Invalid variable names: "name" (not having $ prefix), "$rate of int" (whitespace not
allowed), "$Age#1" (invalid character #), "$11" (name not starting with alphabet).
Variables are assigned with the "=" operator, with the variable on the left hand side and the
expression to be evaluated on the right.
PHP is a dynamically typed language. There is no need to specify the type of a variable. On
the contrary, the type of a variable is decided by the value assigned to it. The value of a variable
is the value of its most recent assignment.

<?php
$x = 10;
echo "Data type of x: " . gettype($x) . "\n";
$x = 10.55;
echo "Data type of x now: " . gettype($x) . "";
?>

Data Types
The term "data types" refers to the classification of data in distinct categories. PHP has a total
of eight data types
 Integers − Whole numbers, without a decimal point, like 4195.
 Doubles − Floating-point numbers like 3.14159 or 49.1.
 Booleans − Have only two possible values, either true or false.
 NULL − Special type that only has one value: NULL.
 Strings − Sequences of characters, like 'PHP supports string operations.'
 Arrays − Named and indexed collections of other values.
 Objects − Instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
 Resources − Special variables that hold references to resources external to PHP (such
as database connections).
Type Casting
The term "Type Casting" refers to conversion of one type of data to another. Since PHP is a
weakly typed language, the parser coerces certain data types into others while performing
certain operations.

Page | 3
To convert an expression of one type to another, you need to put the data type of the latter in
parenthesis before the expression.
Some of the type casting operators in PHP are −
 (int) or (integer) casts to an integer
 (bool) or (boolean) casts to a boolean
 (float) or (double) or (real) casts to a float
 (string) casts to a string

<?php
$a = 9.99;
$b = (int)$a;
$a = "99";
$b = (int)$a;
$a = 100;
$b = (double)$a;
$a = 100;
$b = (string)$a;
?>

Arithmetic Operators
In PHP, arithmetic operators are used to perform mathematical operations on numeric values.
The following table highlights the arithmetic operators that are supported by PHP.

Page | 4
Comparison Operators
In PHP, Comparison operators are used to compare two values and determine their relationship.
These operators return a Boolean value, either True or False, based on the result of the
comparison.
Additionally, these operators can also be combined with logical operators (&&, ||, !) to form
complex conditions for decision making in PHP programs.

Logical Operators
In PHP, logical operators are used to combine conditional statements. These operators allow
you to create more complex conditions by combining multiple conditions together.
Logical operators are generally used in conditional statements such as if, while, and for loops
to control the flow of program execution based on specific conditions.

Page | 5
If…Else Statement
The if keyword is the basic construct for the conditional execution of code fragments. More
often than not, the if keyword is used in conjunction with else keyword, although it is not
always mandatory.
If you want to execute some code if a condition is true and another code if the sme condition
is false, then use the "if....else" statement.
Syntax:

if (expression)
code to be executed if expression is true;
else
code to be executed if expression is false;

<?php
$a=10;
$b=20;
if ($a > $b)
echo "a is bigger than b";
else

Page | 6
echo "a is not bigger than b";
?>

elseif in PHP
If you want to execute some code if one of the several conditions are true, then use the elseif
statement. The elseif language construct in PHP is a combination of if and else.
Syntax :

if (expr1)
code to be executed if expr1 is true;
elseif (expr2)
code to be executed if expr2 is true;
else
code to be executed if expr2 is false;

<?php
$d = date("D");
if ($d == "Fri")
echo "<h3>Have a nice weekend!</h3>";
elseif ($d == "Sun")
echo "<h3>Have a nice Sunday!</h3>";
else
echo "<h3>Have a nice day!</h3>";
?>

Switch Statement
The switch statement in PHP can be treated as an alternative to a series of if…else statements
on the same expression. Suppose you need to compare an expression or a variable with many
different values and execute a different piece of code depending on which value it equals to.

switch ($x) {
case 0:
echo "x equals 0";
break;
case 1:
echo "x equals 1";
break;
case 2:
echo "x equals 2";
break;
}

Page | 7
Default Case in Switch
A special case is the default case. This case matches anything that wasn't matched by the
other cases. Using default is optional, but if used, it must be the last case inside the curly
brackets.

<?php
$x=10;
switch ($x) {
case 0:
case 1:
case 2:
echo "x between 0 and 2 \n";
break;
default:
echo "x is less than 0 or greater than 2";
}
?>

<?php
$d = date("D");

switch ($d){
case "Mon":
echo "Today is Monday";
break;

case "Tue":
echo "Today is Tuesday";
break;

case "Wed":
echo "Today is Wednesday";
break;

case "Thu":
echo "Today is Thursday";
break;

case "Fri":
echo "Today is Friday";
break;

case "Sat":
echo "Today is Saturday";
break;

Page | 8
case "Sun":
echo "Today is Sunday";
break;

default:
echo "Wonder which day is this ?";
}
?>

for Loop
The for statement is used when you know how many times you want to execute a statement
or a block of statements.

<?php
$a = 0;
$b = 0;

for( $i = 0; $i<5; $i++ ) {


$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>

foreach Loop
The foreach statement is used to loop through arrays. For each pass the value of the current
array element is assigned to $value and the array pointer is moved by one and in the next pass
next element will be processed.

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


echo "Value is $value \n";
}
?>

while Loop
The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression
is found to be false.

Page | 9
<?php
$i = 0;
$num = 50;

while($i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );


?>

do-while Loop
The do-while statement will execute a block of code at least once - it then will repeat the loop
as long as a condition is true.

<?php
$i = 0;
$num = 0;

do {
$i++;
}

while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>

break Statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. It gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.

<?php
$i = 0;

while( $i < 10) {


$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>

Page | 10
Continue Statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not
terminate the loop.
Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


if( $value == 3 )continue;
echo "Value is $value \n";
}
?>

Arrays
An array is a data structure that stores one or more data values having some relation among
them, in a single variable.
 An array in PHP is an ordered map that associates values to keys.
 A PHP array can be used to implement different data structures such as a stack,
queue, list (vector), hash table, dictionary, etc.
The array() Function
The built-in array() function uses the parameters given to it and returns an object of array
type. One or more comma-separated parameters are the elements in the array.
Each value in the parenthesis may be either a singular value (it may be a number, string, any
object or even another array), or a key-value pair. The association between the key and its
value is denoted by the "=>" symbol.

$arr1 = array(10, "asd", 1.55, true);


$arr2 = array("one"=>1, "two"=>2, "three"=>3);
$arr3 = array(
array(10, 20, 30),
array("Ten", "Twenty", "Thirty"),
array("physics"=>70, "chemistry"=>80, "maths"=>90)
);

Using Square Brackets [ ]


Instead of the array() function, the comma-separated array elements may also be put inside
the square brackets to declare an array object. In this case too, the elements may be singular
values or a string or another array.

Page | 11
$arr1 = [10, "asd", 1.55, true];
$arr2 = ["one"=>1, "two"=>2, "three"=>3];
$arr3 = [ [10, 20, 30],
["Ten", "Twenty", "Thirty"],
["physics"=>70, "chemistry"=>80, "maths"=>90] ];

Functions
Like most of the programming languages, a function in PHP is a block of organized, reusable
code that is used to perform a single, related action. Functions provide better modularity for
your application and a high degree of code reuse.
A function may be invoked from any other function by passing required data (called parameters
or arguments). The called function returns its result back to the calling environment.

<?php
# define a function
function sayhello(){
echo "Hello World";
}
# calling the function
sayhello();
?>

Function Parameters
A function in PHP may be defined to accept one or more parameters. Function parameters are
a comma-separated list of expressions inside the parenthesis in front of the function name while
defining a function. A parameter may be of any scalar type (number, string or Boolean), an
array, an object, or even another function.
Example :-

<?php
function addition($first, $second) {
$result = $first+$second;
echo "First number: $first \n";
echo "Second number: $second \n";
echo "Addition: $result";
}

addition(10, 20);

$x=100;
$y=200;
addition($x, $y);
?>

Page | 12
Example :-

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$x = 10;
$y = 20;
$num = addFunction($x, $y);
echo "Sum of the two numbers is : $num";
?>

GET & POST


Since PHP is mostly used for web application development, the data sent by the browser client
is mainly with the GET and POST types of HTTP request methods. The HTTP protocol also
defines other methods for sending the request to the server. They are PUT, DELETE, HEAD
and OPTIONS (in addition to GET and POST methods).
The GET Method
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.

<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";

exit();
}
?>
<form action = "<?php <b>$_PHP_SELF</b> ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

The POST Method


The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.

<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");

Page | 13
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

exit();
}
?>
<form action = "<?php <b>$_PHP_SELF</b> ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

Database Connection

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

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

Page | 14
index.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>GFG- Store Data</title>
</head>
<body>
<center>
<h1>Storing Form data in Database</h1>
<form action="insert.php" method="post">

<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>

<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>

<p>
<label for="Gender">Gender:</label>
<input type="text" name="gender" id="Gender">
</p>

<p>
<label for="Address">Address:</label>
<input type="text" name="address" id="Address">
</p>

<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>

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


</form>
</center>
</body>
</html>

Page | 15
insert.php

<!DOCTYPE html>
<html>

<head>
<title>Insert Page page</title>
</head>

<body>
<center>
<?php

// servername => localhost


// username => root
// password => empty
// database name => staff
$conn = mysqli_connect("localhost", "root", "", "staff");

// Check connection
if($conn === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}

// Taking all 5 values from the form data(input)


$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$gender = $_REQUEST['gender'];
$address = $_REQUEST['address'];
$email = $_REQUEST['email'];

// Performing insert query execution


// here our table name is college
$sql = "INSERT INTO college VALUES ('$first_name',
'$last_name','$gender','$address','$email')";

if(mysqli_query($conn, $sql)){
echo "<h3>data stored in a database successfully."
. " Please browse your localhost php my admin"
. " to view the updated data</h3>";

echo nl2br("\n$first_name\n $last_name\n "


. "$gender\n $address\n $email");
} else{
echo "ERROR: Hush! Sorry $sql. "

Page | 16
. mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>
</center>
</body>

</html>

Questions
Figure 2 shows how a list of facts about Pluto should be displayed in a browser.
The HTML code should:
• underline the heading ‘All About Pluto’
• make alternate lines italic.

The page does not display as intended because there are two errors in the HTML code. Identify
the errors and write the code part to correct the two errors.

Page | 17
Figure 1 shows how a list of facts about London should be displayed in a browser.
The HTML code should:
• display each line with the bullet type shown
• display each fact on a new line
• include the citation shown.

The page does not display as intended because there are two errors in the HTML code. . Identify
the errors and write the code part to correct the two errors.

CSS code can be referenced within HTML documents by using style sheets.
Explain one difference between an external and an internal style sheet.

Page | 18
a) Write down the purposes of the following HTML tags.

Tags Purpose

(i) <hr>

(ii) <br>

(b) Write down HTML code segment to create the following description list.

Java
Object-oriented programming
Pascal
Procedural programming

(c) Consider the following HTML code segment to create a table.


<table border=”1”>
<caption> Marks </caption>
<tr>
<th> Subjects </th>
<th colspan="2"> Marks </th>
</tr>
<tr>
<td> Physics </td>
<td> 89 </td>

Page | 19
<td> 92 </td>
</tr>
</table>

Write down the results rendered on the web browser.

(a) The incomplete HTML code below will be added to the web page to link it to the
external style sheet. [Assume that the name of the external style sheet file is
styles.css]

Complete the following table by writing the missing parts of the HTML code.

Page | 20
Write the output of the following HTML code when rendered by a web browser.

Page | 21
Page | 22

You might also like