Instructor’s Notes Web Data Management PHP Sequential Processing Syntax Web Data Management 152-155 PHP Sequential Processing Syntax Notes Activity Quick Links & Text References PHP tags in HTML Comments General Syntax Declaring Variables Output Mathematical Calculations String Processing Dates Input Variable Scope Pages Pages 48 – 49 Pages Pages 52 – 53 Pages 58 – 59 226 - 227 Pages 60 – 63 Pages 58 – 59 64 – 65 259 – 287 Pages 64 – 65 292 – 307 Pages 54 – 57 Pages 384 – 385 Inserting PHP into HTML To include PHP in your web pages, you need to surround the PHP commands with PHP tags <?php ?> You CANNOT include HTML tags between these tags, only PHP commands Most pages have many PHP tags The Deitel book likes to use PHP to create complete HTML commands <?php echo "<h1>Welcome, $name</h1>"; ?> Note the HTML tags embedded in the string literal (they are NOT HTML tags themselves) Note the variable embedded in the string and that the string is surrounded by quotes Page 1 of 12 Instructor’s Notes Notes Web Data Management PHP Sequential Processing Syntax Activity Murach on the other hand, prefers to embed small PHP tags inside of the HTML <h1>Welcome, <?php echo $name ?></h1> Note that PHP is only used where needed. The PHP is as short as possible Murach explains this technique as allowing web page (HTML) developers to develop pages without knowing a whole lot about PHP. The PHP programmer can work separately on complex PHP and all the HTML programmer has to do is include it (you'll learn about that later) and can focus on the layout and appear of the form. This separates the programmer and web developer tasks, allowing them to work on different components of the site at the same time. I'm not 100% convinced yet, that the two can be completely separated, but we'll work towards that goal and keep the PHP tags short. Comments Same as JavaScript Multiline comments /* Inline comments // */ General Syntax Like JavaScript, PHP IS CASE SENSITIVE All statements end with a semicolon All blocks of statements are surrounded by {curly brackets} Declaring Variables PHP supports six data types: integer, double, boolean, string, array and object Variables ARE NOT declared in PHP You simply type the variable name the first time you need it The type of the variable is determined based on the type of data you store in the variable Variable types can change Variable names start with a $ and can contain letters, numbers, underscore Page 2 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity Output In PHP, you output to the HTML that will be sent to the client browser. echo echo 'My name is ' . $name; echo command's results are inserted into the HTML The command above would insert My name is Volker into the HTML (assuming $name contains “Volker”) The stuff to be echoed can be surrounded by parenthesis, but it's not required (I normally don't) echo's primary advantage over print is its ability to echo a list of values (separated by commas). print can only output one item per command. print print('My name is ' . $name); The parentheses aren’t required here either but they're almost always included in the examples I've seen. print's primary advantage is that it's a function, so it returns a value. In some rare instances, that's necessary (see book page 227) Unless you have a reason, I'd pick one of these output commands and stick with it (be consistent). In general, they're interchangeable. Normally, we will only echo/print a single value or (concatenated) string so the advantages of echo or print are not a factor. Mathematical Calculations Same operators as JavaScript + - * / % Same compound operators as JavaScript ++ -- += -= *= /= %= Integer divided by Integer returns a double Order of Precedence ++ -* / % + - Page 3 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity String Processing String literals can be enclosed in either apostrophes or quotes Murach suggests using apostrophes to speed up processing Quotes need to be scanned for embedded variables even if there are no embedded variables (slower) Remember that HTML can also use either apostrophes or quotes. Choose your string delimiters wisely. Period ( . ) used for concatenation Formatting numbers as strings number_format(value[, places]) Formats numbers with commas if appropriate Rounds to the number of decimal places specified Decimal places designation is optional. If not included, rounds to 0 decimal places printf(“formatting string”, value[s]); Use in place of print or echo (can’t be used inside a string) Formatting string can include string literals and placeholders Provide one value for each placeholder in formatting string Placeholders: source e.g. %5.2f ▪ Starts with % ▪ Followed by field width (optional) ▪ Followed by number decimals (optional) ▪ Followed by field type ♦ %d integer ♦ %f float (number with decimals) ♦ %s ♦ Others available (see source above) ▪ Example: printf("%s is %d years old and makes $%.2f per hour", $empName, $empAge, $empWage); ♦ %s is replaced by the contents of $empName ♦ %d is replaced by the contents of $empAge ♦ %.2f is replaced by the contents of $empWage ♦ Always displays 2 decimals places ♦ Since width is omitted, number only takes up as much room as it needs Page 4 of 12 Instructor’s Notes Notes Web Data Management PHP Sequential Processing Syntax Activity PHP allows you to embed variables inside string literals Usually during output (see below) echo "My name is $name"; String must be surrounded by quotes in order for variable to be interpreted I don't use this much. I simply concatenate variables to literals Can be handy for testing Escape characters allow you insert special or non-printing characters into string literals \n (new line) \' (apostrophe in a string surrounded by apostrophes) (even works in strings surround by apostrophes) \” (quotes in a string surround by quotes) NOTE: escape characters only work in string literals surrounded by quotes (not apostrophes) Page 5 of 12 Instructor’s Notes Notes Web Data Management PHP Sequential Processing Syntax Activity String functions (see web or book for details) empty($str) strlen($str) substr($str, $start[, $len]) strpos($s1, $s2[, $offset] stripos, strrpos, strripos Index of s2 in s1 (starting at offset) Adding “i” makes the search case insensitive Adding “r” searches in reverse str_replace($s1, $new, $s2) str_replace($array, $new, $s2) str_ireplace Replaces $s1 with $new in $s2 preg_replace(‘pattern’,’repWith’, $myString) Use a regular express pattern to replace string with a different string pattern may include /g to replace all chr(value) creates a single character string given an ASCII numeric value ord($char) returns the ASCII value of a character implode and explode are used to convert an array to a string or a string to an array (see book) strcasecmp($s1, $s2) compares string case insensitive strnatcmp($s1, $s2) compares strings of numbers correctly (2 < 10) trim, ltrim, rtrim remove white space (int) $strvalue converts a string to an integer (normally, this is done automatically by PHP) (float) $strvalue converts to a double Page 6 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity Dates Timestamps are old school and will cause problems with dates after 2038 (see 2038 problem in book or Google) Still used in existing web pages, but new development should use the DateTime class There are functions that can convert from timestamp to DateTime Note PHP (in XMAPP) installs with an initial time zone of Europe/Berlin meaning all your times (all dates for a few hours a day) will be off by 5-6 hours. To fix this, you have to modify the php.ini file. Navigate to the xampp/php folder on your USB drive Open php.ini in Notepad++ or Notepad Find (Ctrl-F) zone Change Europe/Berlin to America/Chicago Save and close If you have Apache (XAMPP) running, you’ll have to stop and restart it to get the changes to take effect. $now = new DateTime(); $now = new DateTime('2011-01-20 12:00:00'); //10:30 pm $now must be instantiated -> invokes a class method $now->setDate(2011, 1, 20); $copy = clone $now; Alias for new DateTime( ) Can also be used with string parameter $now->setTime(22, 30, 0); Time is optional. If not included, set to 12:00:00 am $now = date_create(); Instantiate the class and immediate assign current date and time Creates a new date variable $copy that has the same values as $now Can't use (just) = That simply makes two pointers pointing to the same instance $due->modify('+3 weeks'); Modifies the date value in $due (must be instantiated) See timestamp strtotime function for list of valid modify options. Page 7 of 12 Instructor’s Notes Notes Web Data Management PHP Sequential Processing Syntax Activity echo $due->format('Y-m-d h:i'); Converts a date to a string and formats Format Codes D – Mon l – Monday n – 3 (month) m – 03 (month) M – Jan F – January j – 5 (day) d – 05 (day) Y – 2011 g – 5 (hours, 12) G– 5 (hours, 24) h – 05 (hours, 12) H – 05 (hours, 24) i – 07 (minutes) s – 09 (seconds) a – am/pm A – AM/PM T – time zone (EST) c – 2012-01-25T13:30:15+00:00 r – Thu, 25 Jan 2012 13:30:00 +0200 NOTE: PHP Dates can be compared using relational operators: if($Date1 <= $Date2) is legal in PHP (but not in JavaScript) DateInterval Class Used for DateTime math $now->add('P10D'); Adds 10 days to $now $now->sub('P10D'); Subtracts 10 days from $now $span = $now->diff($anotherDate); $span will be defined as a DateInterval Determines the interval between $now and $anotherDate DateIntervals can be assigned to a variable $myInterval = new DateInterval('P10D'); DateInterval Codes P – starts all interval strings nY – n years nM – n months nW – n weeks nD – n days T – beginning of a time interval nH – n hours nM – n minutes nS – n seconds Page 8 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity One interval can contain many codes $myInterval = new DateInterval('P2WT10H30M'); 2 weeks, 10 hours, 30 minutes Note the “T” that starts the time Formatting Intervals Intervals can be formatted (for display) Display results of a diff echo $myInterval->format('%m months %d days'); Interval formatting codes %R - + or – representing future or past %y – years %m – months %d – days %h – hours %i – minutes %s – seconds Any characters that appear in the format that are not formatting codes appear as typed. Page 9 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity Input Because PHP runs on a server, it has no mechanism for getting input from a user All PHP input comes from an HTML form POST or GET Murach recommends using GET when the results page only displays data and using POST when the results page modifies data. The results page has access to the form variables via the super global (always defined) arrays $_POST or $_GET Only one or the other array will contain values These arrays are associative arrays (remember from JavaScript?). They include key/value pairs The keys are the determined by the names of the HTML form objects ( name='school') Each form object is automatically converted to an array element EXCEPT: Radio buttons (they all share the same name, remember?) Check boxes are only assigned $_POST/$_GET array elements if they are checked. They only send their values if they are checked. You can use $_POST or $_GET array elements directly in your PHP, but Murach generally transfers values from the array to variables. $school = $_GET['school']; There is also a $_REQUEST super global array that combines $_GET, $_POST, $_COOKIES Only one of $_GET, $_POST should contain values We won’t be using $_COOKIES for a while (if ever) Avoids need to use an If statement to figure out which super global array was filled I use $_REQUEST exclusively. Page 10 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity Murach doesn’t mention it, but PHP comes with a function called extract extract($_REQUEST); This command converts the key/value array pairs into variables with the same name as the key whose values are already set to whatever the value was in the array See array notes in Unit 2 Example: Let’s say the form has two text fields named firstName and lastName Let’s further say the user enters Volker and Gaul into these text boxes. $_REQUEST['firstName'] contains 'Volker' $_ REQUEST ['lastName'] contains 'Gaul' extract($_REQUEST); would automatically create a variable $firstName containing 'Volker' and another variable $lastName containing 'Gaul' extract creates variables for every value sent from the input form. PHP includes a handy function: the print_r function print_r displays (no echo necessary) all the elements (key/value pairs) of an array The results aren’t pretty, but they’re very handy for debugging. I’ll often insert this command at the very beginning of the receiving page: print_r($_REQUEST); to verify that all my data has been transferred from the input form and to remind me what the input field names are. Page 11 of 12 Instructor’s Notes Web Data Management Notes PHP Sequential Processing Syntax Activity Variable Scope Variables defined (used) inside PHP tags (see below) are available to any PHP tag on the page. Pages often have many PHP tags These types of variables are considered global variables However, those variables are NOT accessible inside php functions UNLESS, you use a separate line to designate you want access to a global variable global $a; Provides access to a global variable, $a, inside a function Variables declared inside a function have local scope. They are only available to that function. Super Global variables ($_REQUEST, $_POST and $_GET are examples, there are many others) are available everywhere Page 12 of 12