Introduction to PHP

advertisement
Introduction to PHP
LIS 458
adapted from M. Menzin’s CS 333 handouts
N. Veilleux
PHP is a scripting language (therefore interpreted). This means that it will work its way from the
top of the page to the bottom happily unless it encounters incorrect code along the way. Typing
in frequent “echo” commands can help you diagnose where the code dies.
You compose your script in Notepad or other editor, save it as a filename.php file and then FTP
it to your favorite web server (web.simmons.edu). It does not need to go in your public_html or
cgi-bin directory.1
PHP scripts live in (X)HTML pages. They go between <?php and ?>
firstScript.php on eLearning
<html>
<head>
<title>PHP TEST</title>
</head>
<body>
<?php
echo '<p>Hello World!<br>';
?>
</body>
</html>
Variables: persist from script to script in one html page; this means you can interleave html
between delimited php code blocks and the variable names and stored values will persist from
one block to the other.
All variables in php start with $ e.g. $myVar
Statements:
Statements are separated with a semi-colon.
Braces { } are used to create a block of statements.
Constants
PHP also has constants.
<?php define “AUTHOR” = “YourNameHere” ?>
And later on
<?php echo AUTHOR ?>
Note that when the constant is defined it is named inside quotes, but when it is used it is not! It
is conventional to name constants in all caps.
1
If you have a telnet (terminal) window open, you can test your code by typing php filename.php.
Concatenation is with the dot ( . or period) operator.
$greet = “Hello ”
$who = “World”
Then $greet.$who
is Hello World
BTW, the double and single quotes must be correctly paired but it generally doesn’t matter
which pair you use. (Fancy left/right quotes from Word docs won’t work so don’t cut and paste
from here)
Echo statements produce output to the screen.
echo($greet . $who);
will print Hello World to the screen (notice that the space is part of $greet and doesn’t happen
automatically. BTW, the ( )s are optional for echo and we could write
echo $greet,$who;
Here is another simple script: Notice that the quotes surround the text to be echoed but not the
variable $x. Also notice that the value in $x persists through the next <?php ?> section.
html >
<head>
<title>PHP Script #2 - Simple Variables</title>
</head>
<body>
The purpose of this script is to illustrate persistence of variables.
We enter our first php script and initialize $x to "hello".<br />
<?php
$x='hello ';
echo "<p>The value of our variable is " .$x. "</p>";
?>
<br />Now we merrily exit our script, start another script, print the value
and then reset $x to "world".<br />
<?php
echo "<p>The value of our variable before re-setting is ".$x."</p>";
$x='world';
echo '<p>The value of our variable after resetting is '.$x ."</p>";
?>
Notice that the value of $x persists from one script to another!
</body>
</html>
secondScript.php
Comments
//This is a comment to the end of the line.
/* This is a multi-line comment */
Arithmetic operators
PHP has the usual arithmetic operators: + - * / ++ etc.
and the logical operators are && (AND) , || (OR) , and ! (NOT)
See w3schools.com for details. http://w3schools.com/php/default.asp
Flow of control
Conditional Statements
There is the usual if/else conditional (forward branching) statement. If there is more than one
statement to be executed then the relevant block of code is enclosed in { }’s
if (condition)
<html>
code to be executed if condition is true;
<head>
else
<title>PHP Script #3 - and If/Else and the
code to be executed if condition is false;
Usual Loops</title>
</head>
Logical conditions are enclosed in parentheses.
<body>
The purpose of this script is to illustrate the
usual loop stuff.<br />
Loops
In addition to the loops you are used to there (for,
<?php
while, and do_until) is a special one (foreach) for
$i=0;
looping through arrays.
if($i ==0)
echo '$i is what it should be <br />';
 while (condition) { … }
else
echo 'trouble! < br/>';
 do { … } while (condition) (NOTE: like
the while loop but iterated at least once).
while ($i < 5) {
echo '$i = ' .$i. '.<br />';
$i++;

for (init condition; test condition; increment) {
…}
(for loop statements executed in the following
order: a) init (once, before loop), b) test condition
before each iteration and c) increment at the end
of each iteration)
thirdScript.php

}
for($i=10; $i <=100; $i+=10)
echo '$i = ' .$i. '.<br />';
?>
</body>
</html>
foreach($arrayName as $variable) { code }
See http://w3schools.com/php/php_ref_array.asp and following pages.
Arrays and More on Loops
Arrays hold sequences of values (a list) and, like all other variables in PHP begin with a $.
Arrays may be indexed with integers (starting at 0 not 1) or with keys.
The number of entries in the array $A is given by count($A)
For indexed arrays, you can “walk through” the array with a for loop.
for($i=0; $i <=10; $i++)
echo ‘arrayName[$i]. '<br />';
<head>
<title>PHP Script #4 - Basic Arrays</title>
</head>
<body>
The purpose of this script is to illustrate the usual stuff about
walking through arrays.<br />
<?php
for($i=0; $i < 5; $i++)
$numbers[$i]=2*$i; # just to put some numbers in the test array
for($i=0; $i < 5; $i++)
print('Entry for index '.$i.' is '.$numbers[$i].'.<br />');
?>
</body>
</html>
fourthScript.php
or may be associative arrays, that is indexed by something other than integers.
Arrays in PHP come with a foreach iterator that is especially useful for associative arrays.
The beauty of foreach is that you don’t need to index thru the array based on an integer index,
e.g. with the labels on input fields from forms (see below).
fifthScript.php
<HEAD>
<TITLE> arrays: indexed and associative</TITLE>
</HEAD>
<BODY>
<?php
//indexed array (0..4)
$person = array('Edison', 'Wankel',
$creator = array('Light bulb'
=>
'Rotary Engine' =>
'Toilet'
=>
'Crapper');
'Edison',
'Wankel',
'Crapper');
echo "<BR>" . $person[0] . " ". $person[2];
echo "<BR>" . $creator['Light bulb'];
echo "<BR>" . $creator[$person[0]];
?>
</body>
</html>
Notice that for defining arrays, whether associative arrays or arrays indexed by numbers,
 the => is used instead of = for assignment,
 array( ) is a constructor that makes an array (list) for you,
 The entries are separated by commas, and
 the statement is terminated with a semi-colon (also not a surprise.)
If you have an associative array such as $newUser, then
$NU_Names = array_keys($newUser);
$NU_Values = array_values($newUser);
Defines two new arrays holding, respectively, the keys(names) and values of $NewUser.
Associative Arrays for HTML Forms
GET and POST from HTML forms
$_GET and $_POST are ‘superglobal’ variables (every file knows about them) which hold the
information passed to them when a script is accessed with a GET or POST.
If your form has named elements (radio button, text , etc.), e.g. myName, and myAge and your
form was posted to a php script, you can pull that information in using an associative array. e.g.
$_POST[‘MyName’]
$_POST[‘MyAge’] will be the values in the text box,etc.
That is, since get and post both send name-value pairs,
$_GET[‘the name of the element in single quotes’] and
$_POST[‘the name of the element in single quotes’] are those values.
Now you have grabbed the values from the form and put them into two php variables.
Functions
Of course php has the ability to define functions.
The syntax is
function myFunction($foo, $bar)
{
…….}
For example:
function array_item($ar, $key){
//if $ar is $_POST
// this function can be used to make sure the items got sent
// and then return the value (see full example in posting from forms
if (array_key_exists($key, $ar)) return ($ar[$key]);
}
An example of reading data from an HTML Form and displaying it.
You will need two files:
PrototypeForm_very_basic.html and php_connect_read_forms.php
PrototypeForm_very_basic.html
<html>
<head>
<title> Form for DBMS Course </title>
<!-- PROTYPE FORM BY M.S.MENZIN, ADAPTED BY N.M. VEILLEUX, 11/19/10 LIS458 -->
</head>
<body>
<p>Please fill in two words - one in each box.</p>
<form id='formName' name='formName'
method = 'post'
action ="php_connect_read_forms.php">
<!--text boxes -->
<input type="text" name="field1" id="field1" value="FILL IT IN!" size="20"
/>Put your first word here!<br />
<input type="text" name="field2" id="field2" value="FILL IT IN!" size="20"
/>And your second word here!<br />
<!-- A submit button will send the form, via get or post to the method
specified in the form tag -->
<input type="submit" name="submitbutton" value="OK" />
</form>
</body>
</html>
php_connect_read_froms.php
<html>
<head>
<title>Simple Form Processing 1</title>
<!-<!-<!-<!-<!--
Kofler 'Definitive Guide to MySQL, 2nd edition –ch.11-p.396 -->
to get data sent with a POST, and put it in an array for future processing.
While this script merely sends the info back with an echo, the values might
equally well be used in a select or insert command: see other scripts -->
The form which sends the data is PrototypeForm_very_basic.html -->
-->
-->
<?php
//The function array_item takes the posted values and puts them in the array $ar.
function array_item($ar, $key)
{ //first we make sure the items got sent via post, and then return the value
if (array_key_exists($key, $ar)) return ($ar[$key]);
}
?>
</head>
<body>
<?php
//$_POST and $_GET are super global arrays in php; they receive values sent by post, get.
//$_POST and $_GET are ASSOCIATIVE arrays; the key is the name of the form element sent.
// The next steps are to unload the posted information
//The first line copies the value of 'submitbutton' into the variable $MY_submitbutton
$MY_submitbutton = array_item($_POST, 'submitbutton');
//Next we copy the value of the form element 'field1' into the variable $MY_f1, etc.
$MY_f1 = array_item($_POST, 'field1');
$MY_f2 = array_item($_POST, 'field2');
//Finally we echo them back to the user:
echo "<html><head><title>Echoing from a form></title></head><body>";
echo "<p>field1 contains ". $MY_f1. "</p>\n";
echo "<p>field2 contains ". $MY_f2. "</p>\n</body></html>";
?>
</body>
</html>
Finally, a php script that reads in input from an HTML form (similar to
PrototypeForm_very_basic.html but the reference to the php file must be edited) and inserts the
information into a database as a new row. Select statement as you saw last week.
<HTML>
<HEAD>
<?php
//The function array_item takes the posted values and puts them in the array $ar.
function array_item($ar, $key)
{ //first we make sure the items got sent via post, and then return the value
if (array_key_exists($key, $ar)) return ($ar[$key]);
}
?>
</HEAD>
<BODY>
<?php
// connect to database. Make sure this works first and then you can remove “Attempting”
$h = 'sorjuana.simmons.edu';
$u = 'veilleux';
$p = '0523672';
$s = '45801fa10_veilleux';
echo 'Attempting ';
$db = mysql_connect($h,$u,$p) or die('unable' . mysql_error($db));
echo 'Connected ';
mysql_select_db($s,$db) or die ('unable' . msql_error($db));
// first sql query: get the previous row's pk
$sql = "select artistID from artist order by artistID DESC limit 1";
$result = mysql_query($sql);
if($result ==0)
echo("<B>Error ".mysql_errno().":".mysql_error()."</b>");
else {
$row_array = mysql_fetch_row($result);
$lastPK = $row_array[0];
}
// second sql query: insert new information
$MY_submitbutton = array_item($_POST, 'submitbutton');
$MY_f1 = array_item($_POST, 'field1');
$MY_f2 = array_item($_POST, 'field2');
$artID = $lastPK + 1;
$sql = "insert INTO artist (ArtistID, First, Last) values ('$artID','$MY_f1','$MY_f2')";
$result1 = mysql_query($sql);
if($result1 ==0)
echo("<B>Error ".mysql_errno().":".mysql_error()."</b>");
// continued on next page
// next sql query: select to see result of insert
$sql = "select * from artist";
$result = mysql_query($sql);
if($result ==0)
echo("<B>Error ".mysql_errno().":".mysql_error()."</b>");
else {
echo ("<table>");
for($i=0;$i<mysql_num_rows($result);$i++){
$row_array=mysql_fetch_row($result);
echo("<TR>");
for($j=0;$j<mysql_num_fields($result);$j++){
echo("<TD>".$row_array[$j]."</TD>");
}
echo("</TR>");
}
echo "</TABLE>";
}
?>
</body>
</html>
Download