Web Programming with PHP (2). PHP Scripts o every PHP script is a collection of one or more statements; these statements appear as a collection of names,

Slides:



Advertisements
Similar presentations
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Introduction to C Programming
VBA Modules, Functions, Variables, and Constants
Learning Web development. 3(+1) Tier architecture PHP script Remote services Web Server (Apache, IIS) Browser (IE, FireFox, Opera) Desktop (PC or MAC)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to PHP. PHP Origins Rasmus LerdorfRasmus Lerdorf (born Greenland, ed Canada) PHP originally abbreviation for ‘Personal Home Pages’, now ‘PHP.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Intermediate PHP (1) Data Structures, Functions, Basic OO & Error Handling.
Scripting Languages and PHP. Origins Rasmus Lerdorf ‘Personal Home Pages’. Zeev Surashi and Andi Gutmans Open Source PHP version 4 Full information on.
Guide To UNIX Using Linux Third Edition
JavaScript, Third Edition
Introduction to C Programming
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Introduction to PHP. PHP PHP is the Hypertext Pre-processor –Script language –Embedded into HTML –Runs as Apache module –Can use DB (MySQL, Oracle, Microsoft.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Intermediate PHP (2) File Input/Output & User Defined Functions.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Introduction to PHP (1) Background, Data Types, Control Structures & Functions.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
JavaScript, Fourth Edition
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
UFCE8V-20-3 Information Systems Development 3 PHP (1) : Data Types, Control Structures, Data Structures, String Handling & Input/Output.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Introduction to PHP. PHP Origins Rasmus LerdorfRasmus Lerdorf (born Greenland, ed Canada) PHP originally abbreviation for ‘Personal Home Pages’, now ‘PHP.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Scope, Objects, Strings, Numbers
JavaScript Syntax and Semantics
Scripts & Functions Scripts and functions are contained in .m-files
Agenda Control Flow Statements Purpose test statement
Topics Introduction to File Input and Output
PHP.
Basics (Cont...).
C Programming Getting started Variables Basic C operators Conditionals
Intro to PHP.
Web Programming with PHP (2)
Topics Introduction to File Input and Output
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

Web Programming with PHP (2)

PHP Scripts o every PHP script is a collection of one or more statements; these statements appear as a collection of names, numbers and special symbols; o individual statements are terminated by a semicolon (;) and blocks of statements are contained within curly brackets ({.. }); o statements can be simple (e.g. print or echo) while others can be grouped statements (e.g. the if {.. } elseif {.. } else {.. } block) o PHP can use literal values such as numbers and blocks of text (e.g. 9 or “some text”) or give names to specific expressions (e.g. variables, functions or classes) o operators are used to join values, usually one value to the left of the operator and one to the right (e.g )

Data Types (1) o PHP has eight different data types – 5 basic and 2 composite types and 1 resource type o The 5 basic data types are: -integers : whole numbers in the range -2,147,483,648 to +2,147,483,647 on 32-bit architecture. Can be octal (prefixed by 0), decimal and hexadecimal (prefixed by 0x) -floating-point : real or doubles (decimal), can be written using base 10 notation (e.g == 3.9e3) -strings : sequence of characters contained by single (‘..’) or double (“..”) quotes. Within double quotes variables are replaced by their values (interpolated). Escape sequences are used to include special characters within double quoted strings (e.g. \” to include a double quote and \\ to include a backslash) -booleans : the boolean data type evaluates to either true or false (e.g. $a == $b will evaluate to true if both variables contain the same value, false otherwise -null : a special data type that stands for a lack of value. Often used to initialize or reset variables.

Data Types (2) o arrays : are a composite data type that collect values into a list. The values of the array elements can be text, a number or even another array. Arrays can be from 1 to any number of dimensions. - arrays are referenced using square [.. ] brackets. <?php $cities[0] = “London”; $cities[1] = “Bath”; $cities[2] = “Bristol”; print (“I live in $cities[2]. \n”); ?> - an array can be indexed using a string value for the index (called associative array or hash) and are useful in situations where there is a need to collect different types of data into one array. (e.g. $userInfo [“name”] = “Kevin”; ) - array elements containing other arrays are used to build multi-dimensional arrays. <?php $modules = array( “ISD”=>array( “Joe”, “Tim”, “Mary” ) “ISDP”=>array( “Bob”, “Tom”, “Sue” ) ); print ($modules[“ISD”][2]); ?>

Data Types (3) o objects : are another composite data type fully supported by php. - php supports standard object-oriented (OO) methodologies and techniques such as inheritance - the ability to derive new classes from existing ones and inherit or override their attributes and methods. encapsulation - the ability to hide data from users of the class (the public, protected and private keywords.) special methods - for instance, code that is automatically run when a object is created (constructor) or destroyed (destructor). polymorphism – overloading a function so that a function call will behave differently when passed variables of different type. - a good introducton to OO programming using php can be found at o resources : are a data type that hold handles to external resources such as open files or database connections.

Control statements are a means of executing blocks of code depending on one or more conditions. if (expression) {..} : the simple if statement takes the following form – if (expression) { this block gets executed if the expression evaluates to true } if (expression) {..} elseif (expression) {..} else {..} : the compound if statement takes the following form – if (expression1) { this block gets executed if expression1 is true } elseif (expression2) { this block gets executed if expression1 is false and expression2 is true } else { this block gets executed if both expression1 and expression2 are false } ? operator : acts as a shortened version of the if {..} statement. It takes the followng form - conditional expression ? true expression : false expression; Control Structures (1)

Control Structures (2) switch (expression) {case expression.. case expression.. default} : similar to the if.. elseif.. else structure where a single expression is compared to a set of possible values and if a match is made, the block following the match is executed. The break statement can be used to jump out of a switch structure. A default expression can be used to execute code if none of the expressions evaluates to true. o Loops – allow for the repetition of blocks of code until a condition is met. while (expression) {..} : when first reached the expression is evaluated and if true the block of code following the expression is executed, otherwise the block is skipped. The break statement can be used to break out of a while block. The continue statement can be used to return control to the beginning of the block. do {..} while (expression) : is a way of delaying the decision to execute a code block until the end. for (initialization; continue; increment) {..} : used to carry out a block a code a specific number of times. foreach (array as key=>value) {..} : provides a formalized method for iterating over arrays.

Control Structures (3) exit, die and return : the exit statement is used to stop execution – it is useful when an error occurs and it could be harmful to continue execution; the die statement is similar to exit but can be followed by an expression which is sent to the browser just before the script is aborted, for instance $fp = fopen(“somefile.txt”, “r”) OR die(“Could not open file”); the return statement can be used within functions (see following section) but can also be used with the include statement. If used within a script, it stops execution within the current script and returns control to the script that made a call to include. That is, when a include is used, the included script may return prematurely.

PHP Functions (1) : inbuilt function library (700+) - Basic tasks –String Handling –Mathematics – random numbers, trig functions.. –Regular Expressions –Date and time handling –File Input and Output - And more specific functions for- –Database interaction – - MySQL, Oracle, Postgres, Sybase, MSSQL.. –Encryption –Text translation –Spell-checking –Image creation –XML etc.etc.

PHP Functions (2) : user defined functions - Declaring a function - functions are declared using the function statement, a name and parenthesis () e.g function myfunction() {…..} - functions can accept any number of arguments and these are separated by commas inside the parenthesis e.g function myFunction(arg1, arg2) {…..} - the following simple function prints out any text passed to it as bold <?php function printBold($text){ print(" $text "); } print("This Line is not Bold \n"); printBold("This Line is Bold"); print(" \n"); print("This Line is not Bold \n"); ?>

- the return statement - at some point the function will finish and is ready to return control to the caller - execution then picks up directly after the point the function was called - it is possible to have multiple return points from a function (but this will reduce code readability) - if a return statement includes an expression, return(expression), the value of the expression will be passed back - example <?php function makeBold($text){ $text = " $text "; return($text); } print("This Line is not Bold \n"); print(makeBold("This Line is Bold"). " \n"); print("This Line is not Bold \n"); ?> PHP Functions (3) : user defined functions

- values and references - for most data types, return values are passed by value - for objects, discussed next week, return values are returned by reference - the following function creates a a new array of 10 random numbers between 1 and 100 and passes it back as a reference <?php function &getRandArray() { $a = array(); for($i=0; $i<10; $i++) { $a[] = rand(1,100); } return($a); } $myNewArray = &getRandArray(); ?> PHP Functions (4) : user defined functions

- scope (1) - scoping is way of avoiding clashes between variables in different functions - each code block belongs to a certain scope - variables within functions have local scope and are private to the function - variables outside a function have a global scope <?php $a = 1; /* global scope */ function test(){ echo $a; /* reference to local scope variable */ } test(); ?> The above example will output nothing because the $a inside the function has local scope PHP Functions (5) : user defined functions

- the global keyword can be used to access variables from the global scope within functions <?php $a = 1; $b = 2; function Sum(){ global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> - The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. PHP Functions (6) : user defined functions

- arguments - functions expect arguments to to be preceded by a dollar sign ($) and these are usually passed to the function as values - if an argument has a & sign in front - it is treated as a reference - the following example shows an argument passed as reference <?php function stripCommas(&$text){ $text = str_replace(",", "", $text); } $myNumber = "10,000"; stripCommas($myNumber); print($myNumber); ?> PHP Functions (7) : user defined functions

-default values - a function can use a default value in an argument using the = sign to precede the argument - consider the follwing example <?php function setName($FirstName = "John", $LastName = "Smith"){ return "Hello, $FirstName $LastName!\n"; } ?> - So, to greet someone called John Smith, you could just use this: setName(); - To greet someone called Tom Davies, you would use this: setName("Tom", "Davies"); - To greet someone called Tom Smith, you would use this: setName("Tom"); PHP Functions (8) : user defined functions

Input / Output & Disk Access (1) o Reading and Writing to Files Communicating with files follows the pattern of opening a stream to a file, reading from or writing to it, and then closing the stream. fopen(..) : the fopen function opens a file for reading or writing. The function expects the name of a file and a mode e.g. fopen (“c:/temp/myfile.txt”, “r”); which opens a file called myfile.txt in the directory “c:/temp” in the “read” mode File read/write modes : rreading only wwrite only, create if necessary, discard previous content aappend to file, create if necessary, start writing at end r+reading and writing w+reading & writing, create if necessary, discard previous content a+reading & writing, create if necessary, start writing at end

Input / Output & Disk Access (2) fclose (resource file) : used to close a file. feof (resource file) : as a file is read, php keeps a pointer to the last place in the file read; the feof function returns true if the end of file is reached. fgetcsv(resource file, integer length, string separator) : used for reading comma-separated data from a file. The optional separator argument specifies the character to separate fileds’ If left out, a comma is used. fgets(resource file, integer length) : returns a string that reads from a file. It will attempt to read as many characters – 1 as specified by the length value. A linebreak character is treated as a stopping point, as is the end of the file. fwrite(resource file, string data, integer length) : writes a string to a file. The length argument is optional and sets the number of bytes to write.

PHP Resources PHP Home : Learning PHP : PHP Extension & Application Repository (PEAR) : pear.php.netpear.php.net PHP Resource Index : php.resourceindex.comphp.resourceindex.com PHP Builder : Installing Apache/PHP/MySQL (xampp) : windows.html windows.html