You are on page 1of 63



PHP Syntax
PHP code is executed on the server, and the plain HTML result is sent to the browser.

Basic PHP Syntax

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with <? and end with ?>. For maximum compatibility, standard form (<?php) are recommended rather than the shorthand form.

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. Note: The file must have the .php extension. If the file has a .html extension, the PHP code will not be executed.

Comments in PHP
In PHP, use // to make a single-line comment or /* and */ to make a large comment block.
<html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>

PHP Variables

Variables in PHP
Variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again in your script All variables in PHP start with a $ sign symbol.

The correct way of setting a variable in PHP:

Syntax:$var_name = value; Example: $marks = 81.5; $msg = Hi there!;

Dont forget the $ sign at the beginning of the variable. In that case it will not work.

PHP is a Loosely Typed Language

In PHP a variable does not need to be declared before being set. Dont have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on how they are set. In PHP the variable is declared automatically when you use it.

Variable naming rules

A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

Working with variables

<html> <head> <title>Working with variables</title> </head> <body>


$name =Suzana"; echo "Hello $name";

?> </body></html>

Assigning values to variables

To assign a value to variable, regardless of the variable type, use equal sign (=) called assignment operator For example:<html> <head><title>Assign value to variables</title> </head> <body> <?php

$street = "jln raja musa mahadi"; $city = "ipoh"; $zip = 31400; echo "The address is: <br> $street <br>$city $zip";
?> </body></html>

Operators and Expressions

Operator, operand and expressions

An operator is a symbol or series of symbols that, when used in conjunction with values, perform an action and usually produces a new value. An operand is a value used in conjunction with an operator. There are usually two or more operands to one operator. An expression is any combination of functions, values and operators that resolves to a value.

The assignment operator (=)

Each time a variable was declared, the assignment operator consists of a single character =. The assignment operator takes the value of the right-side operand and assigns it to the left-side operand.

Arithmetic operators
Operator + / * % Name Addition Subtraction Division Multiplication Modulus Example 10 + 3 10 3 10 / 3 10 * 3 10 % 3 Sample Result 13 7 3.33333333333 30 1

The concatenation operator

Is represented by a single period(.) Treating both operands as string, this operator appends the right-side operand to the leftside operand For example;
"Hello". " World"

Hello World

Comparison Operators
Perform comparative tests using their operands and return Boolean value TRUE if the test is successful or FALSE if the test fails. Some of the comparison operators; ==, !=, >, <, >=, <=


Variables offer flexible way of storing data because you can change their values and the type of data they store at any time during the execution of scripts. Constant a value that must remain unchanged throughout scripts execution. Using define() function define(constantName, value);

<?php define("YEAR", 2008 ); echo " It is the year ".YEAR; ?> The result: It is the year 2008

Control Structures

Three (3) types of control structure in programming

Sequence Selection / Conditional
If statement If..else statement Switch statement

For loop While loop Do..while loop

Conditional If statement
The If keyword is used to perform the basic conditional PHP test to evaluate an expression for a Boolean value. The statement will be executed only when the expression is true <?php $num = 7; if($num % 2 != 0) { $msg = "$num is an odd number."; echo $msg; } ?>

If..else statement
The PHP else keyword can be used with if statement to provide alternative code to execute in the event that the tested expression is found to be false

<?php $num = 7; if($num % 2 != 0) echo "$num is an odd number."; else echo "$num is an even number."; ?>

Switch statement
<?php $num = 2; switch($num) { case 1 : echo "This break; case 2 : echo "This break; case 3 : echo "This break; default: echo "This } ?>

is case 1"; is case 2"; is case 3";

is default";

For Loop
<?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" ; ?>

While Loop
<?php $i = 0; $num = 50; while($i < 10) { $num--; $i++; } echo "Loop stopped at $i<br> \$num is now $num" ; ?>

Do..while Loop
<?php $i = 0; $num = 50; do { $num--; $i++; }while($i < 1); echo "Loop stopped at $i<br> \$num is now $num" ; ?>


A piece/block of PHP code that can be executed once or many times by the PHP scripts. Function is a subprogram that contains lines of code that will be called many times

Creating PHP function

All functions start with the keyword "function()" Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) Add a "{" - The function code starts after the opening curly brace Insert the function code Add a "}" - The function is finished by a closing curly brace

Syntax:function func_Name(arguments) { lines of code; return (value); }

Output Using function <html><body> 25 <?php function quadratic() { $a = 5; $result = $a * $a; function echo $result; } echo Using function<br>; quadratic(); function called ?> </body></html>

Example 1:-

Output Using function <html><body> 25 <?php 49 function quadratic($a) { $result = $a * $a; function echo $result <br>; } echo Using function<br>; quadratic(5); function called quadratic(7); function called ?> </body></html>

Example 2:-

Example 3:-


<html><body> Using function <?php 25 function quadratic($a) 49 { $result = $a * $a; function return ($result); } echo Using function<br>; echo quadratic(5); function called echo <br>; echo quadratic(7);function called ?> </body></html>

Code segment in func.php <?php function quadratic($a) { $result = $a * $a; return ($result); } ?> <form action= func.php method = get> Key in one number : <input type = text name=no ><br> <input type = submit value = Calculate> </form> <?php if(isset($_GET[no])== TRUE) { $quadr = quadratic($_GET[no]); echo Quadratic = $quadr ; } ?>

Using include( ) and require() function

Both functions work the same way, with one relatively insignificant difference. If the include() function fails, the PHP script generates a warning but continues to run. If require() fails, it terminates the execution of the script. Both include() and require() incorporate the file referenced into the main file.


What is an Array?
A collection of multiple values assembled into one overriding variable. An array can consist of numbers and/or strings, which allow this one variable to hold exponentially more information than a simple string or number.

Syntactical Rule for Arrays

Arrays also have name, derived using the same conventions as variable The differences is that array contain multiple elements. An element consists of an index or key and a value. Generally, array looks the same as other variable, except that an array include a key in square brackets [ ] when referring to particular values.

Creating an Array
Formal method of creating an array is to use the array( ) function. Syntax:$list = array(apples, grape, oranges); OR $list = array( 1=> apples, 2=> grape, 3=> oranges);

<html><head><title>Soup!</title></head> <body>Delicious Soups.. Yummy:<br> <?php //create an array $soups = array ( Monday => Mushroom, Tuesday => Chicken Chili, Wednesday => Vegetarian);
//display the array echo <p>$soups</p>;

//display the contents of array print_r ($soups); echo <p>; var_dump ($soups); ?> </body></html>

Adding items to an Array

In PHP, once an array exists, an extra elements can be added to the array with that assignment operator (=) Either specify the key of the added element or not Example:To add two items to the $list array
$list[] = pears;

$list[] = pineapples;
$list[3] = pears; $list[4] = pineapples;



Accessing Array Elements

One way to retrieve a specific element (or value) from an array, that is to refer to its index:\
echo The total of your order comes to $array[0];

The fastest an easiest way to access all the values of an array is to use foreach loop. foreach ($array as $key => $value) { echo Key is $key. Value is $value; }

<html><head><title>Soup!</title></head> <body>Soup of the day:<br> <?php //create an array $soups = array ( Monday => Mushroom, Tuesday => Chicken Chili, Wednesday => Vegetarian, Thursday' = Chicken Noodle, Friday = Tomato, Saturday = Cream of Broccoli); //display each key and value of an array foreach($soups as $day => $soup) { echo $day: $soup<br>; }?> </body></html>

Creating Multidimensional Array

Example: $fruits = array(apples, grape, oranges); $meats = array(steak, burger, chicken chops); $groceries = array( fruits => $fruits, meats => $meats, other => peanuts, cash => 30.00);

File handling with PHP

Displaying directory files

Special PHP functions can be used to display a list of all the files contained within any directory on your system. It must be opened with opendir() function Once open, a loop can assign all the file names to a variable list using readdir() function It is important to remember to close the directory when the loop has completed using closedir() function

Copying & renaming files

Files on your system can be copied to any location using PHPs copy() function that required two arguments: the full path of the source file to be copied, and the full path of the desired location where the copy is to be placed. You can also renamed files on your system using PHPs rename() function that required two arguments: the original name of the file and the new name which it will be changed.

Deleting files
The PHP unlink() function permanently deletes the files specified as its argument (if it is a valid file name)

Opening and Closing files

The PHP fopen() function is used to read text from files, write text to files and append text to files. It required two arguments: the file name and a mode in which to operate.

File modes can be specified as one of the six options: Mode Purpose
r r+ w Opens the file for reading only. Places the file pointer at the beginning of the files. Opens the file for reading and writing. Places the file pointer at the beginning of the file. Opens the file for writing only. Places the file pointer at the beginning of the file and truncates the file to zero length. If the file does not exist this will attempt to create it. Opens the file for reading and writing. Places the file pointer at the beginning of the file and truncates the file to zero length. If the file does not exist this will attempt to create it. Opens the file for writing only. Places the file pointer at the end of the file. If the file does not exist this will attempt to create it. Opens the file for reading and writing. Places the file pointer at the end of the file. If the file does not exist this will attempt to create it.



Reading a file
A file can be opened with the fopen() function A file can then be read with a function called fread() A files length can be found using the filesize() function fclose() function used to close file.

Writing a file
A new file can be written, or text appended to an existing file, using the PHP fwrite() function.


Connecting PHP to MySQL

To connect to MySQL, the PHP mysql_connect() function requires three arguments. mysql_connect() function returns TRUE if the connection succeeds, or FALSE if the attempt fails. Syntax:mysql_connect(hostname, username, password);

<?php $hostname = localhost; $username = root; $password = ;


//connecting to MySQL $conn = mysql_connect($hostname, $username, $password) OR die(Failed to connect to MySQL!!); //choosing database from MySQL $dbaseName = dbPelajar; $db = mysql_select_db($dbName); if($db == FALSE) echo Failed to used the database $dbaseName; else echo $dbaseName database succeeds to used; ?>

Listing database in MySQL

The equivalent of SQL show databases command in PHP requires the use of three special functions. mysql_list_dbs() returns set of information about all database The total number of databases can be determined using mysql_num_rows() The name of each database can be extracted from result by mysql_tablename()

Listing table names

Similar to mysql_list_dbs() function, the PHP mysql_list_tables() returns a result set of information about all tables in a database. Each table name can be extracted from result and its row number as the arguments to the by mysql_tablename() function

<?php $conn = mysql_connect(localhost, root, ) OR die(Sorry Could not connect to MySQL!!); $r1 = mysql_list_dbs($conn) for($rw = 0; $rw < mysql_num_rows($r1); $rw++) { $thisDB = mysql_tablename($r1, $rw); $list .= <b> . $thisDB . </b><br>; if($thisDB != mysql) { $r2 = mysql_list_tables($thisDB); for($nm=0; $nm < mysql_num_rows($r2); $nm++) $list .= - .mysql_tablename($r2,$nm). <br>; } } echo $list; ?>


Executing SQL query from PHP

mysql_query() function returns TRUE if the query succeeds, or FALSE if the attempt fails. Syntax:mysql_query(query);

Example: $query = SELECT * FROM tblPelajar; $result = mysql_query($query)

<?php $conn = mysql_connect(localhost, root, ) OR die(Sorry Could not connect to MySQL!!); $r1 = mysql_select_db(dbPelajar, $conn) OR die(Sorry No such database in MySQL!!);


$query = SELECT idPlj, namaPlj FROM tblPelajar;

$r = mysql_query($query, $conn); while($rw = mysql_fetch_array($r)) { echo ID : .$rw[idPlj]; echo Nama Pelajar : .$rw[namaPlj] . <br>; }