Instructor s Notes Web Data Management PHP Sequential Processing Syntax. Web Data Management PHP Sequential Processing Syntax

Similar documents
WEBD 236 Web Information Systems Programming

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

Chapter 10 How to work with dates

WEBD 236 Web Information Systems Programming

How to work with dates

Chapter 10. How to work with dates. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C10

Chapter 17. Fundamental Concepts Expressed in JavaScript

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Creating HTML files using Notepad

PHP by Pearson Education, Inc. All Rights Reserved.

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

CSC Web Programming. Introduction to JavaScript

What is PHP? [1] Figure 1 [1]

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

PHP. Introduction. PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Access Intermediate

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

BEGINNER PHP Table of Contents

MIT AITI Python Software Development

Expressions and Variables

Mr. Monroe s Guide to Mastering Java Syntax

These are notes for the third lecture; if statements and loops.

Chapter 2 Working with Data Types and Operators

Introduction to Bioinformatics

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Web Scripting using PHP

Access Intermediate

Introduction to: Computers & Programming: Review prior to 1 st Midterm

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Lecture 12. PHP. cp476 PHP

CSCE 120: Learning To Code

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Python Review IPRE

Full file at

Introductory ios Development

CGS 3066: Spring 2015 JavaScript Reference

3 The Building Blocks: Data Types, Literals, and Variables

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

JavaScript Functions, Objects and Array

Values and Variables 1 / 30

RTL Reference 1. JVM. 2. Lexical Conventions

In addition to the primary macro syntax, the system also supports several special macro types:

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

introjs.notebook March 02, 2014

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

CIS 110: Introduction to Computer Programming

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

T H E I N T E R A C T I V E S H E L L

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

Instructor s Notes Java - Beginning Built-In Classes. Java - Beginning Built-In Classes

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Ex: If you use a program to record sales, you will want to remember data:

corgi Language Reference Manual COMS W4115

My Favorite bash Tips and Tricks

Expr Language Reference

Lecture 2 Tao Wang 1

Variables and Typing

Typescript on LLVM Language Reference Manual

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

MCIS/UA. String Literals. String Literals. Here Documents The <<< operator (also known as heredoc) can be used to construct multi-line strings.

JavaScript I Language Basics

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

Adobe EchoSign Calculated Fields Guide

ARG! Language Reference Manual

CS 106 Introduction to Computer Science I

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Zend PHP Certification Study Guide. Copyright 2005 by Sams Publishing. International Standard Book Number: Warning and Disclaimer

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CERTIFICATE IN WEB PROGRAMMING

Web Scripting using PHP

YOLOP Language Reference Manual

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

RMS Report Designing

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

4 Programming Fundamentals. Introduction to Programming 1 1

Client-Side Web Technologies. JavaScript Part I

PHP 1. Introduction Temasek Polytechnic

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

I. Variables and Data Type week 3

Section 1. How to use Brackets to develop JavaScript applications

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

PHP Online Training. PHP Online TrainingCourse Duration - 45 Days. Call us: HTML

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

4. Java Project Design, Input Methods

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

PHP. Interactive Web Systems

Unit 3. Constants and Expressions

Transcription:

Instructor s Web Data Management PHP Sequential Processing Syntax Web Data Management 152-155 PHP Sequential Processing Syntax Quick Links & Text References PHP tags in HTML Pages Comments Pages 48 49 General Syntax Pages Declaring Variables Pages 52 53 Output Pages 58 59 226-227 Mathematical Calculations Pages 60 63 String Processing Pages 58 59 64 65 259 287 Dates Pages 64 65 292 307 Input Pages 54 57 Variable Scope 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 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 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 4 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 5 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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(); Instantiate the class and immediate assign current date and time $now = new DateTime('2011-01-20 12:00:00'); Time is optional. If not included, set to 12:00:00 am $now = date_create(); Alias for new DateTime( ) Can also be used with string parameter $now->settime(22, 30, 0); //10:30 pm $now must be instantiated -> invokes a class method $now->setdate(2011, 1, 20); $copy = clone $now; 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 6 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 7 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 8 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 9 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 10 of 11

Instructor s Web Data Management PHP Sequential Processing Syntax 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 11 of 11