LIS651 lecture 1 PHP basics Thomas Krichel 2005-03-19.

Slides:



Advertisements
Similar presentations
LIS651 lecture 3 taming PHP Thomas Krichel
Advertisements

LIS651 lecture 1 PHP basics, database introduction Thomas Krichel
LIS651 lecture 3 functions and arrays Thomas Krichel
LIS651 lecture 1 arrays functions & sessions Thomas Krichel
LIS651 lecture 0 Gathering and showing data Thomas Krichel
LIS651 lecture 3 numbers, Boolean, control flow Thomas Krichel
LIS651 lecture 3 functions & sessions Thomas Krichel
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Session 1 & 2BBK P1 Module5-May-2007 : [‹#›] PHP: Moving On..
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
CMT Programming Software Applications
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
JavaScript, Third Edition
Operations & Strings CSCI 116 Web Programming I. 2 Arithmetic Operators Arithmetic operators are used to perform mathematical calculations.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
Computer Programming for Biologists Class 2 Oct 31 st, 2014 Karsten Hokamp
PHP : Hypertext Preprocessor
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
PHP Workshop ‹#› Data Manipulation & Regex. PHP Workshop ‹#› What..? Often in PHP we have to get data from files, or maybe through forms from a user.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 2 - Algorithms and Design
PHP Controlling Program Flow Mohammed M. Hassoun 2012.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Programming Languages Meeting 13 December 2/3, 2014.
Slide 3-1 CHAPTER 3 Conditional Statements Objectives To learn to use conditional test statements to compare numerical and string data values To learn.
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.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Strings, output, quotes and comments
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
CSE123 Lecture 3 Files and File ManagementScripts.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
Session 2: PHP Language Basics iNET Academy Open Source Web Development.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Introduction to PHP and MySQL (Creating Database-Driven Websites)
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
LIS651 lecture 1 PHP basics, database introduction
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Intro to PHP & Variables
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
Number and String Operations
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
Data Manipulation & Regex
Unit 3: Variables in Java
Presentation transcript:

LIS651 lecture 1 PHP basics Thomas Krichel

today we work with –text –numbers –flow control –array and then we reorganize the shop

string a piece of text in PHP is called a string. A string is often surrounded by single quotes. print 'I want beer'; $want='beer'; print 'I want $want'; // prints: I want $want If you want to use the values of variables, use double quotes print "I want $want"; // prints: I want beer

single and double quotes You can use single quotes to quote double quotes print 'She wrote: "I want beer." and sighed.'; // prints: She wrote: "I want beer." and sighed. and vice versa print "She wrote: 'I want beer.' and sighed"; // prints: She wrote: 'I want beer.' and sighed. Sometimes it is not obvious when to put single quotes, double quotes, and when to leave them out. If one thing does not work, try something else.

the backslash escape The backslash is used to quote characters in a that otherwise are special. print 'Don\'t give me bad beer!'; $kind='bock'; $beer='Festbock' print " $beer "; // prints: Festbock The backslash itself is quoted as \\ –print "a \\ against beer consumption"; –// prints: a \ against beer consumption

backslash in double quoted chars \n makes the newline character \r make the carriage return (no use in Unix) \t makes the tab (seldomly used in HTML) \$ makes the dollar (used in the shop). –$amount='1.50'; –print "you owe \$$amount per bottle."; –// prints: you owe $1.50 per bottle. If the backslash was not there $ would be considered to be a variable.

trim() trim() removes the whitespace at the beginning and the end of the string. It returns the transformed string $input " 5 "; $output=trim($input); print "|$input|"; // prints: |5| whitespace is any of the following characters –the blank character –the newline –the carriage return –the tabulation character

strlen() strlen() returns the length of the string $zip=trim($_POST['zipcode']); $zip_length=strlen($zip); print $zip_length; // hopefully, prints 5

strtolower() and friends strtolower() makes lower case $up='BEER' $low=strtolower($up); print $low; // prints: beer strtoupper() makes upper case print strtoupper('beer'); // prints: BEER ucwords() capitalizes every word $name="grossWald bier"; print ucwords($name); // prints: GrossWald Bier

substr substr(string,start,amount) extracts parts of a string. string is the string to extract from. start is the position to start extracting from. 0 means the beginning of string. If start is negative, it counts from the end. amount is how much to extract. $blabla="To keep a long story short, I have a hangover."; $blah=substr($blabla,0,27); print "$blah..."; // prints: To keep a long story short... print substr($blabla,-18,18); // prints: I have a hangover.

str_replace str_replace(string,substring,replace) a substring. string is the string, substring is the substring, replace is the replacement. $html='my Bruch '; $new_html=str_replace($html,'myclass','beer'); print $new_html; // prints: my Bruch

sprintf() sprintf(format,string) returns string formatted according to format format. format is a special string. There are many formating options. They can be complicated. We do not study this further, but there is a useful example. –$third=1/3; –print $third; –// prints: –print sprintf("%.2f",$third); –// prints: 0.33

strip_tags() strip_tags() removes HTML tags $input=" But weiser"; print strip_tags($input); // prints: Butweiser $in=" "; print strip_tags($in) // prints nothing, hurray!

htmlentities() htmlentities() makes HTML entities out of special chars in HTML.,&, and " are transformed $in="What does the tag do?"; print htmlentities($in); // prints: What does the <div> tag do?

addslashes() if a variable read from a form, say, for example a user name Antoine d'Amstel, contains a single or double quote, this can be very problematic in certain later treatments. Use addslashes() to add slashes to user input that may contain slashes. stripslashes() does the opposite.

regular expressions Regular expressions are the most powerful string manipulation tools known to man. They are the cornerstone of digital library work. I hope to cover some of them later. For now, just know that they exist. Now we turn to numbers.

numbers Numbers are set without the use of quotes. You can +, -, * and / for the the basic calculations. There also is the modulus operator %. It gives the reminder of the division of the first number by the second print 10 % 7; // prints 3 Use parenthesis for complicated calculations $pack=2 * (10 % 7); print "a $pack pack"; // prints: a 6 pack

other number functions abs() calculates the absolute value print abs(-3)// prints: 3 print abs(3)// prints: 3 number_format() formats numbers. When you want two digits only, use as follows –$number=1234,5678 –print number_format($number,2); –// prints 1234,56 Details at

geeky increment/decrement ++ is an operator that adds one. The value of the resulting expression depends on the position of the operator $a=4; print ++$a;// prints: 5 print $a;// prints: 5 $b=4; print $b++;// prints 4 print $b // prints 5 -- works in the same way

variable names Variable name must start with a letter or underscore. They can contain letters, digits and underscores. The following are examples of illegal names –$2drunk –$bottle-content Variable names are case sensitive. I use lowercase only and add underscores in long names. It is good to give variables meaningful names.

concatenation This is done with the. operator. $cost=5.23; $message='This costs '. $cost; print $message; // prints: This costs 5.23 PHP sees that 5.23 is a number but will treat it as a string for this purpose.

geeky combined operators There are some combined operators that change a value and set it to the new one. For example –$a+=$b ; is the same as –$a=$a+$b; Same effect for -=, *=, /=, %=, and.= –$a="I want "; –$b="Balitka 8"; –$a.=$b; –echo $a;// prints: "I want Baltika 8"

Boolean value Every expression in PHP has a Boolean value. It is either 'true' or 'false'. All strings are true except –the empty string –the string "0" All number are true except –0 –0.0 example $a=5-4-1; // $a is false

expression An expression is something you write down. Expressions that are evaluated in Boolean often use comparison operators. $beer == "grosswald"; // checks for equality note difference from $beer="grosswald"; // this is always true Other comparisons are < smaller than<= smaller or equal than > larger than >= larger or equal than

if() if() evaluates an expression and if true, executes a block of code surrounded by curly brackets. if($drunk) { print "dont\'t drive!\n"; } Note you don't need to indent the block as done above, but the way Thomas has done it there is pretty much standard, so do it in the same way.

if() and else if you have an if() you can add an else block of code to execute when the condition is false if($sober) { print "you can drive\n"; } else { print "check if you are fit to drive\n"; }

if and elseif You can build chain of conditions if($pints_drunk==0) { print "You are ok to drive\n"; } elseif($pints_drunk<3) { print "Don't use the car, get on your bike\n"; } elseif($pints_drunk<=6) { print "Take a cab home\n"; } else { print "Call the local hospital!\n"; }

logical operators 'and' is logical AND. 'or' is logical OR. if(($brand=='Budweiser') or ($brand="Sam Adams")) { echo "Commiserations for buying a lousy beer"; } # where is the mistake in this piece of code? These can be combined. Use parenthesis if((($pints) > 4 and ($vehicle=='car')) or (($pints > 6) and ($vehicle=='bicycle'))) { print "order a cab!" } 'not' is Boolean not.

variable types Variables in PHP have types. Common types include is_numeric() is_string() is_int() is_float() They all return a Boolean value. They can be used to check the nature of a variable.

while() while() { } executes a piece of code while the condition is true $count=0; while($count < 100) { print "Пиво без водки -- деньги на ветер! "; $count=$count+1; # don't forget to increment $count! }

for() loops for() takes the following form, by example How many cans are there in a six pack? Answer: <?php // initial condition ; terminal check ; instruction at the end of loop for($count=0; $count <=10; $count=$count+1) { # note the semicolon above, it is a weird thing! print " \n"; } ?>

Arrays The variables we have looked at up until now are scalars. They can only contain one piece of data. Arrays are variables that can contain one that one piece of data. –For example, a six pack in conveniently represented as an array of cans of beer. –For another example, a class is a group of people, each having a name, a social security number, etc.

numeric arrays An numeric array has key value pairs where the keys are numbers. $good_beers[0]="Baltika 8"; $good_beers[1]="Bruch Festbock"; or as follows $lousy_beers=array("Miller Lite", "Sam Adams", "Budweiser"); print $lousy_beers[0];// prints: Miller Lite print $lousy_beers[2];// prints: Budweiser

string arrays Sometimes you need data structured by a string. For example for a price list. $price['Grosswald Export']=1.45; $price['Bruch Festbock']=1.74; // the array $price has strings as keys An equivalent way to declare this is $price=array('Grosswald Export' => 1.45, 'Bruch Festbock' => 1.74);

count() count() returns the size of an array $price['Grosswald Export']=1.45; $price['Bruch Festbock']=1.74; $product_number=count($price); print "We have $product_number products for you today."; // prints: We have 2 products for you today.

counting in numeric arrays For numeric arrays, you can add members very simple without keeping track of number. $beers=("Karlsberg", "Bruch") ; $beers[]="Budweiser"; // beer now has Karlberg, Bruch and Budweiser

looping through an array foreach() loops through an array. An example illustrates print " \n"; foreach ($price as $item => $euro_amount) { print " $item \n"; print " €$euro_amount \n"; } print " "; This prints the full price list. But it could also do the whole form. This is fabulous!

the well-aligned price table $l_r=array('left','right'); $count=0; // counter of elements printed print " \n"; foreach ($price as $item => $euro_amount) { print " <td align=\"$l_r[$count % 2]\""; print "$item"; $count++; print " \n €$euro_amount \n";

$count++; } print " \n"; // This produces something like // // Grosswald Export // €1.45 // Bruch Festbock // €1.74 //

multiple arrays Example $products[0]['name']="Grosswald Pilsener"; $products[0]['price']=1.56; $products[1]['name']="Grosswald Export"; $products[1]['price']=1.34; $products[2]['name']="Bruch Landbier"; $products[2]['price']=1.22;

restructure the shop Instead of having two files, one with HTML, the other with PHP, let us have just one. It's easier. One cool thing to help that is cool is $_SERVER[PHP_SELF] It gives the file name of your script in the form. As you change your script file name, you do not need to change the name of the form submitted.

define some variables $form_greet=' Please place your order '; $form_top=" "; $form_submit=' '; $submit_check=' '; $form_bottom=' '; $order_head=" Results of your order \n"; $order_bottom="Thank you for your order. We will ship when we get your check. Prosit!\n ";

printing results if($_GET['submitted']) { $total_euro=0; print $order_head; foreach($_GET as $number => $amount) { if($amount > 0 and $products[$number]) { $pay=$amount*$products[$number][price]; print "$amount bottles of "; print $products[$number][name]; print " is €$pay "; $total_euro+=$pay; }

print results, start form printing part $total_dollar=$total_euro*$euro_rate; $total_dollar=number_format($total_dollar,2); print "The euro rate is $euro_rate \n"; print "Your bill is \$$total_dollar\n "; } else { // print the form print $form_greet; print $form_top; $product_count=0; foreach ($products as $prod) { print "\n "; print $prod['name']; print " ";

final part, printing the form print "<input type=\"text\" name=\""; print $product_count; print "\" maxlength=\"2\" size=\"2\"/>"; print print $prod['price']; print " \n"; $product_count++; // don't forget! } print $submit_check; print $form_submit; print $form_bottom; }

We include a hidden element in the form to see if it was submitted We start the script we check for submission if($_POST['submitted']) { // work on the data that was submitted } else { // print form } check for submission

Thank you for your attention! Please switch off machines b4 leaving!