Vous êtes sur la page 1sur 63

UNIT 3 :PHP PROGRAM

F5224 WEB PROGRAMMING

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

$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 & Expressions

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

Example
10 + 3 10 3

Sample Result
13 7

/ *
%

Division Multiplication
Modulus

10 / 3 10 * 3
10 % 3

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 left-side operand For example;
"Hello". " World"

returns
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; ==, !=, >, <, >=, <=

Constant

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

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

Control Structures

CONTROL STRUCTURES
Three (3) types of control structure in programming
Sequence Selection / Conditional
If statement If..else statement Switch statement

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

Functions

FUNCTION
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

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

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

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

Output

Using function 25 49
function

Example 3

Output

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

ARRAY

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

or

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

FILES 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 AND 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 Opens the file for reading only. Places the file pointer at the beginning of the files.

r+ w

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.

w+

a+

READING A FILES
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 FILES
A new file can be written, or text appended to an existing file, using the PHP fwrite()function.

PHP & MYSQL

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


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

Vous aimerez peut-être aussi