creativity and computation lab: module 2 week 2: intro to php
TRANSCRIPT
Creativity and Computation
Lab: Module 2
Week 2: Intro to PHP
Today we will cover several aspects of the middleware
package PHP (PHP Hypertext Preprocessor):
• What PHP can do by itself• Accessing MySQL with PHP• Scripting with PHP to create a
database driven website
We probably won’t get through everything in this
presentation today. Just relax, dive in, and absorb
as much as you can.
We’ll continue next week.
If you need more info, or just help, a great place to go is the main PHP site:
www.php.net
That link and others are now up on the CC Lab Site:
a.parsons.edu/~sven/cc/lab
along with your homework assignments and a bunch of PHP scripts you can cut and
paste from.
First, some basic stuff about PHP:
• It’s a scripting language, just like HTML or Javascript.
• It’s saved as text, just like HTML• It’s open-source, so there is lots of
code available online• There are also many tutorials
online
The main thing PHP is used for is “middleware”; to connect the
web to the database:
Today, instead of working directly from the command line as we did with MySQL, the PHP
files will be treated like web files and stored in your public_html directory. We will run and test
them through the normal Apache HTTP server (web).
The most important thing is that you try things as we go
along. They won’t always work, but keep trying.
You will become more comfortable with coding the
more you do it.
Let’s dive right in. Go to the CC Lab site and get the basic PHP script (blank.php). Go to the
<a.parsons.edu> command line and create a folder in your public_html folder called
“cclab”. Store “blank.php” there and run it from a browser.
When you run the file, it is blank. But notice there is PHP code in the file:
<?php?>
Types of comments:
in HTML:<!-- blah -->
in PHP:# blah// blah/* blah spanning two lines in PHP */
Why do we comment?<!-- Start of PHP -->BlahBlahBlah<!-- End of PHP -->
(to remind us of what we did)
What are variables?
Variables are holders used to temporarily store values.
They exist in all prograsmming
languages.You used them in Pbasic; you will use them in
PHP.
Variable rules in PHP:
• Variables start with “$”• Character after “$” cannot be
number• Variable names are case
sensitive• Variables can be assigned
values using “=“ sign
Built-in variables in PHP:<?php
// Echo the script name.echo "You are running the file <b>$PHP_SELF</b>.<br /><br />\n";
// Echo the user's information.echo 'You are viewing this page using:<br /><b>', $HTTP_USER_AGENT, '</b><br />from the IP address ', $REMOTE_ADDR;?>
Strings in PHP
• $first_name = ‘Harry’• Use echo() or print() to print
out:echo “Hello, $first_name”
orecho $first_name
String example:<?php// Create the variables.$first_name = ’Harry';$last_name = ’Smith';$book = ’Grand Fool of the Night';
// Print the values.echo "The book <i>$book</i> was written by $first_name $last_name.";?>
Concatenating strings:
In PHP, the “.” is used to concatenate strings.
echo ‘Design and ‘.’Technology’;
Will print “Design and Technology”
What will these series of commands print?
$firstname = ‘Harry’; $lastname =‘Smith’;
$fullname = $firstname.$lastname;
echo $fullname;
What about $firsthame .= “Smith”;
echo $firstname;
In PHP variables aren’t specific to a string or a number:
<?php$a = "Hello World!";$b = 4;$c = 4.5;?>
The variable $a is a STRINGThe variable $b is a INTEGERThe variable $c is FLOAT
Single vs. double quotation marks:Use ‘single quotes’ to enclose simple strings:<?phpecho 'this is a simple string';
echo 'You can also have embedded newlines instrings this way as it isokay to do';
// Outputs: Arnold once said: "I'll be back"echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newlineecho 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $eitherecho 'Variables do not $expand $either';?>
Double quotations:
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:Escaped characterssequence meaning\n linefeed (LF or 0x0A (10) in ASCII)\r carriage return (CR or 0x0D (13) in ASCII)\t horizontal tab (HT or 0x09 (9) in ASCII)\\ backslash\$ dollar sign\" double-quote
But the most important feature of double-quoted strings is the fact that variable names will be expanded:
<?php$beer = 'Heineken';echo "$beer's taste is great"; // works, "'" is an invalid character for varnames. Outputs: Heineken’s taste is greatecho "He drank some $beers"; // won't work, 's' is a valid character for varnames. Outputs: He drank some $beersecho "He drank some ${beer}s"; // worksecho "He drank some {$beer}s"; // works?> //Outputs: He drank some Heinekens
Conditionals and Operators
Arithmetic OperatorsExample Name Result• -$a Negation Opposite of $a.• $a + $b Addition Sum of $a and $b.• $a - $b Subtraction Difference of $a and $b.• $a * $b Multiplication Product of $a and $b.• $a / $b Division Quotient of $a and $b.• $a % $b Modulus Remainder of $a divided by
$b.
Comparison Operators:
Example Name Result• $a == $b Equal TRUE if $a is equal to $b.• $a === $b Identical TRUE if $a is equal to $b, and they are of the
same type. (introduced in PHP 4)• $a != $b Not equal TRUE if $a is not equal to $b.• $a <> $b Not equal TRUE if $a is not equal to $b.• $a !== $b Not identical TRUE if $a is not equal to $b, or they
are not of the same type. (introduced in PHP 4)• $a < $b Less than TRUE if $a is strictly less than $b.• $a > $b Greater than TRUE if $a is strictly greater than $b.• $a <= $b Less than or TRUE if $a is less than
equal to or equal to $b.• $a >= $b Greater than TRUE if $a is or equal to
greater than or equal to $b.
HTML forms with PHP:Here’s a sample HTML form using PHP
<html><body><h4>Tizag Art Supply Order Form</h4><form action="process.php" method="post"><select name="item"><option>Paint</option><option>Brushes</option><option>Erasers</option></select>Quantity: <input name="quantity" type="text" /><input type="submit" /></form></body></html>
<--- The line that tells which php file to target. (process.php)
The PHP File (of the form):
Here’s a sample PHP form which processes the data sent from the HTML form:
<html><body><?php$quantity = $_POST['quantity'];$item = $_POST['item'];echo "You ordered ". $quantity . " " . $item .
".<br />";echo "Thank you for ordering from Tizag Art
Supplies!";?></body></html>
The Output
Process.php would display this to the screen:
You ordered 6 brushes.
Thank you for ordering from Tizag Art Supplies!
Arrays
An array is a data structure that can hold store many items. Think of it as a
storage bin with labeled compartments.
This array is called “Fruit”
0 1 2 3
apple orange pear cherry
First array entries always start with 0!
How we describe arrays in code:
So we can say that Bin 0 of Fruit is apple, OR (in code):
Fruit[0] = appleFruit[1] = orangeFruit[2] = pear
“Fruit”
0 1 2 3
apple orange pear cherry
(more) Arrays:
In PHP, we make Arrays like this:
$fruit = array(apple,orange,pear,cherry);
This creates the array.Now we can access the info inside the array:echo $fruit[0];
This output: apple
Associative Arrays use a key system:$mdays = array (
"January" => 31,"February" => 28,"March" => 31,"April" => 30,"May" => 31,"June" => 30,"July" => 31,"August" => 31,"September" => 30,"October" => 31,"November" => 30,"December" => 31);
If $mname = January, what does $mdays[$mname] = ?
Example:
echo $mdays[June];
Will output: 30
Now for some fancy stuff:Multidimensional Arrays
$fruits = array ( "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"), "numbers" => array(1, 2, 3, 4, 5, 6), "holes" => array("first", 5 => "second", "third"));
Lets draw out what this would look like (on the white board);
How to sort arrays:
Simple arrays:sort($Fruit);Will sort alphabetically, or in asc order, if all the entries are numbers:
Fruit[0] = appleFruit[1] = cherryFruit [2] = orangeFruit[3] = pear
Associative arrays:asort($mdays);This will sort the entries in the same way, but keep the corresponding keys
For and while loops
Sometimes we want to go through a lot of information quickly. Lets say we want to print out all of the elements in our fruit array to see which fruits are available.
We can do it this way:
echo Fruit[0];
echo Fruit[1];
echo Fruit[2];
echo Fruit[3];
This would print out all of our fruits, but what if we have 1000s of entries? That would be a pain, no?
We use loops to make this easier..
Let’s say the Fruit array now has 2345 entries…
While loop
$i = 0; <---intializerwhile($i < 2345){ <---condition must be trueecho Fruit[$i]; $i++; <---incremetor}
This would print all entries out one by one! All loops have 3 elements: Intializer, Condition, and Incremetor.
We can simplify even further to make a
FOR loop:
for($i = 0; $i < 2345; $i++) { echo Fruit[$i]; }
Notice this one has all three elements (Initializer, Condition, and Incrementor) all in the first line. It works the same way as a while loop, but is often neater and easier to read.
Connecting to the database:<?php // This file contains the database access information. This file also establishes a connection to MySQL and selects the database.
// Set the database access information as constants.DEFINE ('DB_USER', 'username');DEFINE ('DB_PASSWORD', 'password');DEFINE ('DB_HOST', 'localhost');DEFINE ('DB_NAME', 'sitename');
// Make the connnection and then select the database.$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );mysql_select_db (DB_NAME) OR die ('Could not select the database: ' . mysql_error() );?>
Simple queries to the database First, formulate the question:SELECT$query="SELECT * from $tableName";
INSERT$query="INSERT INTO $tableName (color, speed) values ('$color', '$speed')";
DELETE$query="DELETE FROM $tableName WHERE id = '$id'";
UPDATE$query="UPDATE $tableName SET start_x ='$start_x',start_y = '$start_y',color = '$color',speed = '$speed' WHERE id = '$id'";
It is very important that we ask if there were any errors in our query:
$result =mysql_query($query)OR die("error 3 - query failed");
If(!$result){ //if $result is NOT TRUEEcho “SOMETHING’S WRONG!”;
}
Do something with the results (for SELECT):// check that there are results$num_rows=mysql_affected_rows($link);// output contentif($num_rows>0){ // get info while ($myrow = mysql_fetch_array($result)) { $id=$myrow["id"]; $name=$myrow["name"]; $description=$myrow["description"]; $price=$myrow["price"]; print("$name $price $description"); }}else{ // tell user there's no info print("sorry, no records");}
Your assignment (due next week):
Write a PHP script that accesses information from a database using a while or for loop, puts the information into an array, and outputs it to a web page.
You must make the information and the page formatting somehow personal, so it is clear you did it yourself.
Store the script at:
a.parsons.edu/~user/cclab/insane.php