PHP Programming What we know so far… …and something new.

Slides:



Advertisements
Similar presentations
» PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.
Advertisements

PHP Form and File Handling
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
RAPTOR Syntax and Semantics By Lt Col Schorsch
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
More on PHP Coding Lab no. 6 Advance Database Management System.
Objectives Using functions to organize PHP code
Functions & Arrays. Functions Functions offer the ability for programmers to group together program code that performs specific task or function into.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
PHP Functions Composite Types. Functions  Declaration  function functionName(paramList) {  /* code goes here */ }  paramList is comma-separated list.
PHP String Functions, User Functions and Pulling it All Together Chapters 4 & 5.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
PowerPoint Lesson 3 Working with Visual Elements
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
1 Insert, Update and Delete Queries. 2 Return to you Address Book database. Insert a record.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
1 Introduction to Javascript Peter Atkinson. 2 Objectives To understand and use appropriately some of the basic elements of Javascript: –alert and prompt.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Writing C-shell scripts #!/bin/csh # Author: Ken Berman # Date: # Purpose: display command and parameters echo $0 echo $argv[*]
Week 7. Lecture 2 Functions, Arrays, PHP&MySQL. Function with More than one argument and a return statement For a function to return a value, the return.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
PHP - Basic Language Constructs CSCI 297 Scripting Languages - Day Two.
CONTROL STRUCTURE The if, elseif, and else & switch Statements 1.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, © Copyright 2015, Fred McClurg, All Rights.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Outline Overview Opening a file How to create a file ? Closing a File Check End-of-file Reading a File Line by Line Reading a File Character by Character.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
>> PHP: Insert Query & Form Processing. Insert Query Step 1: Define Form Variables Step 2: Make DB Connection Step 3: Error Handling Step 4: Define the.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Chapter 3 Automating Your Work. It is frustrating when you have to type the same passage of text repeatedly. For example your name and address. Word includes.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
NMD202 Web Scripting Week2. Web site
XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and Conditional Statements Creating a Monthly Calendar.
ADOBE INDESIGN CS3 Chapter 4 WORKING WITH FRAMES.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming javascript arrays.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
File Handle and conditional Lecture 2. File Handling The Files associated with Perl are often text files: e.g. text1.txt Files need to be “opened for.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Creating PHP Pages Chapter 10 PHP Arrays. Arrays An array can store one or more values in a single variable name. An element of an associative accessed.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
PHP. What is PHP? PHP Hypertext Processor – Dynamic web development – Scripting language – Can be procedural or OOP(preferred) – PHP code can be embedded.
CSE 154 LECTURE 16: FILE I/O; FUNCTIONS. Query strings and parameters URL?name=value&name=value...
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
String and Lists Dr. José M. Reyes Álamo.
Session 2 Basics of PHP.
Arrays An array in PHP is an ordered map
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
While Loops BIS1523 – Lecture 12.
Creation, Traversal, Insertion and Removal
String and Lists Dr. José M. Reyes Álamo.
PHP an introduction.
Presentation transcript:

PHP Programming What we know so far… …and something new

Forms Creating a form in html:form Monday/Wednesday Tuesday/Thursday Friday/Sunday Saturday

processing forms … <?php // get form selection $day = $_GET['day']; // retrieve from form // check value and select appropriate item if ($day == 1) { $special = 'Chicken in oyster sauce'; } elseif ($day == 2) { $special = 'French onion soup'; } elseif ($day == 3) { $special = 'Pork chops with mashed potatoes and green salad'; } else { $special = 'Fish and chips'; } ?> Today's special is: … cooking.php

Rewrite with switch <?php // get form selection $day = $_GET['day']; // check value and select appropriate item switch($day) { case 1: $special = 'Chicken in oyster sauce'; break; case 2: $special = 'French onion soup'; break; case 3: $special = 'Pork chops with mashed potatoes and green salad'; break; default: $special = 'Fish and chips'; } ?>

strings Displaying and concatenating: echo 'Items ordered: '. $totalqty. ' ';

logic Relational operators: ==, !=, >, >=, <, <= if ($age >= 21) { echo 'Come on in, we have alcohol and music awaiting you!'; } else { echo "You're too young for this club, come back when you're a little older"; } Conditional operators: &&, ||, !, xor if (($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0) echo $year.’ is a leap year ’ else echo $year.’ is not a leap year ’

Tricky logic A self-testing formself-testing form <?php /* if the "submit" variable does not exist, the form has not been submitted - display initial page */ if (!isset($_POST['submit'])) { ?> " method="post"> Enter your age: <?php } else { /* if the "submit" variable exists, the form has been submitted - look for and process form data */ // display result $age = $_POST['age']; if ($age >= 21) { echo 'Come on in, we have alcohol and music awaiting you!'; } else { echo "You're too young for this club, come back when you're a little older"; } ?>

Increments/decrements/ shorthand notation $total++ same as $total = $total + 1 $total-- same as $total = $total - 1 $line.= ‘more’ same as $line = $line.’more’ $x += 5 same as $x = $x + 5 $answer = ($x == 10) same as: if ($x == 10) $answer = true;

iteration while (condition is true) { do this } do { do this } while (condition is true); for (startval of counter; condition; update counter) { do this }

Drawing tables "> Enter number of rows and columns <?php if (isset($_POST['submit'])) { echo " "; // set variables from form input $rows = $_POST['rows']; $columns = $_POST['columns']; // loop to create rows for ($r = 1; $r <= $rows; $r++) { echo " "; // loop to create columns for ($c = 1; $c <= $columns;$c++) { echo " "; } echo " "; } echo " "; } ?> tables.php

File processing File management activities: –Creating –Opening –Writing data to a file –Reading data from a file –Locking –Deleting –Closing –Misc.

Omelette recipe Open the file and assign it a file handle.file Interact with the file, via its handle, and extract its contents into a PHP variable. Close the file.

Writing to a file <?php // set file to writefile $file = 'tmp/dump.txt'; // open file $fh = fopen($file, 'w') or die('Could not open file!'); // write to file fwrite($fh, "Look, Ma, I wrote a file! ") or die('Could not write to file'); // close file fclose($fh); ?>

File existence <?php // if form has not yet been submitted // display input box if (!isset($_POST['file'])) { ?> " method="post"> Enter file path <?php } // else process form input else { // check if file existsfile // display appropriate message if (file_exists($_POST['file'])) { echo 'File exists!'; } else { echo 'File does not exist!'; } ?>

Multiple file functionsfunctions is_dir() - returns a Boolean indicating whether the specified path is a directory is_file() - returns a Boolean indicating whether the specified file is a regular file is_link() - returns a Boolean indicating whether the specified file is a symbolic link is_executable() - returns a Boolean indicating whether the specified file is executable is_readable()- returns a Boolean indicating whether the specified file is readable is_writable()- returns a Boolean indicating whether the specified file is writable filesize() - gets size of file filemtime() - gets last modification time of file filamtime() - gets last access time of file fileowner() - gets file owner filegroup() - gets file group fileperms() - gets file permissions filetype() - gets file type

Other file functions pp : special uses; will learn on a “need to know” basis –feof: end of file –fgets, fgetss, fgetcsv: read a line at a time –readfile, fpassthru: read whole file –fgetc: read a character at a time –unlink: delete a file –rewind, fseek, ftell: inside the file –flock: locking the file

arrays Composite, or aggregate, data types –Can hold more than one value using the same variable name Examples –Quarterly earnings –$q_earnings = array(3, 6, 1, 4); 3614 [0] [1] [2] [3]

arrays Elements Subscripts or indices How to declare/define How to manipulate elements –Inserting –Reading –Deleting –Displaying –Processing Associative arrays

Defining an array <?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); ?> -or- <?php // define an array $pasta[0] = 'spaghetti'; $pasta[1] = 'penne'; $pasta[2] = 'macaroni'; ?>

Defining an associative array <?php // define an array $menu['breakfast'] = 'bacon and eggs'; $menu['lunch'] = 'roast beef'; $menu['dinner'] = 'lasagna'; ?> -or- <?php // define an array $menu = array(‘breakfast’ => 'bacon and eggs‘, 'lunch' => 'roast beef‘, 'dinner' => 'lasagna‘); ?>

Adding/changing elements Adding –$pasta[4] = ‘rigatoni’; or –array_push($pasta, ‘rigatoni’); –$menu[‘snack’] = ‘fruit’; Modifying –Just reassign the element

Removing elements Removing from the end <?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); print_r($pasta); echo ‘ ’; // remove an element from the end array_pop($pasta); print_r($pasta); ?> pastaarray.php

Removing elements Removing from the front <?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // take an element off the top array_shift($pasta); print_r($pasta); ?>

Adding elements to front <?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // add an element to the beginning array_unshift($pasta, 'tagliatelle'); print_r($pasta); ?>

Strings arrays <?php // define CSV string $str = 'red, blue, green, yellow'; // split into individual words $colors = explode(', ', $str); print_r($colors); ?>

arrays strings <?php // define array $colors = array ('red', 'blue', 'green', 'yellow'); // join into single string with 'and' // returns 'red and blue and green and yellow' $str = implode(' and ', $colors); print $str; ?>

Review functions array_push array_pop array_shift array_unshift explode Implode Also, sort and rsort!

Looping through arrays My favourite bands are: <?php // define array $artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses'); // loop over it and print array elements for ($x = 0; $x < sizeof($artists); $x++) { echo ' '.$artists[$x]; } ?>

A niftier way My favourite bands are: <?php // define array $artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses'); // loop over it // print array elements foreach ($artists as $a) { echo ' '.$a; } ?>

Reading files into arrays