Posts Tagged ‘class 7’

Class 7 – Client-side Quiz Answers & Results

Saturday, November 13th, 2010

Here is the answer key to the Client-side Quiz. If you have questions about the answers, be sure to ask them during class.

Grade frequency breakdown

Grade frequency breakdown

This chart shows how many students scored within 10% of the indicated grades. So, for example, one student scored between 21-30%, two students scored between 51-60%, two more between 61-70%, and so on.

To convert your numerical scores to percentages, see this chart:

For example, if you scored 10 points, you receive a grade of 50%.

Class 7 – The XML declaration in your XHTML code can cause problems if your server has PHP short tags enabled

Sunday, April 11th, 2010

One potential problem that you may come across when putting XHTML code inside your PHP files is that the XML declaration tag may confuse the PHP server.

Short tags

Some PHP servers, including ours, are set up to accept “short tags”, which are shortcut versions of some PHP commands.  For example, on our server, you can either open your PHP script by writing

<?php

Or you can simplify that to

<?

This is a shortcut, “short tag” version of the opening PHP tag that allows lazy developers to type less.

There is another short tag that replaces the normal “echo” command.  For example, a normal echo might look like

<?php echo "arugala"; ?>

And the shortened version of the same command would be

<?= "arugala"; ?>

The problem

A problem arises when we put XHTML code inside a PHP file (a file with the .php extension) because the “xml” tag that we use as the first line of our “bare minimum” XHTML document includes the “<?” in it.

<?xml version="1.0" encoding="utf-8"?>

This confuses the PHP processor, which thinks you intend to use a PHP short tag, which you do not.  You will an error message about a “parse error”.

See this problem in action

The solution

The solution is to encapsulate the “<?” characters inside of a PHP echo statement.  This way you prevent the PHP processor from thinking that those two characters are the start of a PHP opening tag.

<?php echo "<?"; ?>xml version="1.0" encoding="utf-8"?>

See this solution in action

Why you should use PHP short tags

You may be tempted to use PHP short tags.  The conventional wisdom is that it’s a bad idea.  This is because not all servers are set up to support them.

So if you at some point move your code from a server that does support them to a server that doesn’t, your code will cease to work.

This does not fit in with our philosophy of writing code using only those practices that are guaranteed to work with a minimum of fuss.

Class 7 – Introduction to Arrays in PHP

Sunday, November 1st, 2009

To complete the templatizing assignment, you will need to have a good understanding of arrays.  This post is meant to be read in addition to the readings from the assignment post, to give you an introductory description of arrays to help you think about arrays clearly.

Simple arrays

An array is a list of data.  In its simplest form, each element in the list consists of two bits of data: a key and a value. So you can think of an array as a table with two columns: one for the key, and the other for the value of that element in the array.

For example, we could conceptually think of an array containing a shopping list as follows:

An array holding data representing a shopping list

An array holding data representing a shopping list

How to create a simple array in PHP

In PHP, we would create this array using the built-in PHP array() function as follows:

$shoppingList = array(
 "potatos",
 "tomatoes",
 "2% milk",
 "prune butter",
 "organic muesli",
 "eggs",
 "unsalted butter",
 "half-sour pickles",
 "shallots",
 "bananas"
);

Notice that we never have to explicitly state what the key for each row is.  If we don’t specify the key, it is automatically filled in with a number. The first element always has key 0, the second has the key number 1, the third has a key of 3, etc.

So the eighth element in the list, “half-sour pickles”, is automatically assigned a key with the number 7, and so on.

Accessing the elements of an array in PHP

If we wanted to echo the value of the 8th element in the list, we could use the following PHP command:

echo $shoppingList[7];

This would output the text “half-sour pickles”.

If we wanted to add another element containing the word, “hand soap”, to the end of the existing list of elements in the 11th position, we could use the following PHP code:

$shoppingList[10] = “hand soap”;

Alternatively, the following code will also add an element to the end of the existing list of elements in the array:

$shoppingList[] = “hand soap”;

The advantage of this latter code is that it does not require us to hard-code the number to use as the key for the new element in the array.  This makes it a more reusable and flexible technique for adding an element to the end of an array.

Assigning custom keys

Alternatively, we could have explicitly specified the keys we wanted to use for each element in the array by using code like this:

$shoppingList = array(
 9 => "potatos",
 1 => "tomatoes",
 2 => "2% milk",
 8 => "prune butter",
 3 => "organic muesli",
 7 => "eggs",
 4 => "unsalted butter",
 6 => "half-sour pickles",
 5 => "shallots",
 0 => "bananas"
);

In this example, we have overriden the default automatically incrementing key numbering system and are specifying keys in whatever order we like.

Associative arrays

In fact, if we wanted to, we could use strings for keys instead of integers.    This is done in more or less the same was as we just saw used for assigning custom keys to an array.

For example, let’s say we wanted to create an array that held the grades of the students in a class.  We could link up a student’s first name and grade as outlined in this diagram:

An associative array

An associative array

How to create an associative array in PHP

To create an associative array in PHP, based on the diagram above, we would use the following code:

$grades = array(
"Amos" => "A",
"Jack" => "A",
"Susan" => "B",
"Donny" => "C",
"Michael" => "C",
"Joshua" =>    "F"
);

Accessing the elements of an associative array in PHP

If we wanted to echo the grade for Susan, we could use the following code:

echo $grades["Susan"];

If we wanted to add a new element to this array to hold Luis’s grade, a B+, we could used the following code:

$grades["Luis"] = "B+";

Debugging arrays in PHP

If you are working with arrays in PHP and are having problems, it often helps to output the contents of the array using the built-in print_r() function of PHP.

For example, to output the array containing grades that we created above, we could use the following code:

print_r($grades);

Running this code will output the following text to the browser:

Array
(
    [Amos] => A
    [Jack] => A
    [Susan] => B
    [Donny] => C
    [Michael] => C
    [Joshua] => F
    [Luis] => B+
)

This will allow us to easily see the values that are stored inside the array.  And we can use this information to check to see if the values we intended to store in the array are indeed being stored there properly.

Multidimensional arrays

Let’s now imagine that we wanted to store a list of data that had more than just a key and a value.  For example, let’s say we had a list of our favorite classical symphonies, structured as a sort of table of data:

A multidimensional array

A multidimensional array

This has more than just one value associated with each key.  In this case, each key has a list of data associated with it, including “title”, “composer”, “key” and “year” values.  In other words, there is a sub-array of data associated with each key.

How to create a multidimensional array in PHP

So, in order to create such a multidimensional array of data, we create an array filled with arrays:

$symphonies = array(
 array(
 "title"     => "Symphony #1",
 "composer"  => "Jean Sibelius",
 "key"       => "E minor",
 "year"      => "1898"
 ),
 array(
 "title"     =>     "Symphony in C major",
 "composer"  =>     "Richard Wagner",
 "key"       =>     "C major",
 "year"      =>     "1832"
 ),
 array(
 "title"     =>     "Symphony #7",
 "composer"  =>     "Ludwig van Beethoven",
 "key"       =>     "A major",
 "year"      =>     "1811"
 ),
 array(
 "title"     =>     "Symphony #3",
 "composer"  =>     "Anton Bruckner",
 "key"       =>     "D minor",
 "year"      =>     "1873"
 ),
 array(
 "title"     =>     "Symphony #10",
 "composer"  =>     "Dmitri Shostakovich",
 "key"       =>     "E minor",
 "year"      =>     "1953"
 ),
 array(
 "title"     =>     "Symphony #9",
 "composer"  =>     "Antonin Dvořák",
 "key"       =>     "E minor",
 "year"      =>     "1893"
 )
);

In many ways, this array is not so different from the simple shopping list array we created at the beginning of this tutorial.  We have not specified what keys to use for each element in the array, so PHP automatically assigns incrementing integers as the keys.

It just so happens that each element in the list is an array, rather than some text or a number.  That’s why it is called a multidimensional array.

Accessing the elements of an associative array in PHP

To read the values contained within the array, we must bear in mind that we have two arrays.  In our example above of the symphonies, the outer array is a simple array whose keys are integers.  The inner arrays are associative arrays with strings as keys.

To print out the contents of the “composer” field of the third element in the array of symphonies, we could use the following code:

echo $symphonies[2]["composer"];

This would output the text:

Ludwig van Beethoven

And if we wanted to add a new symphony to the list, we could use code like the following:

$symphonies[] = array(
 "title"     =>     "Symphony #3",
 "composer"  =>     "Gustav Mahler",
 "key"       =>     "D minor",
 "year"      =>     "1893"
);

Notice that we are not specifying the key for this new element of the array, so PHP automatically assigns it the next available integer, in this case 6.

Looping through simple arrays

Often, in programming, we want to loop through the elements in an array.  The built-in foreach() function in PHP is very useful for this purpose.

To loop through a simple array, such as the shopping list array we created at the beginning of this tutorial, we can use the foreach loop in the following code.  This will output the value of each element in the array:

foreach ($shoppingList as $item) {
 echo $item . "<br />";
}

Looping through associative arrays

When you have an associative array, as in the student grades example above, you will often be interested not only in the value of each element of the array, but also in its custom key.  To access both the key and the value of each element as you loop through the array, you can use a foreach loop like the following:

foreach ($grades as $name => $grade) {
 echo $name . " got a " . $grade . "<br />";
}

This effectively goes through each element in the $grades array one at a time, and divides it up into two variables: $name and $grade.  $name holds the key, and $grade holds the value.  This loop iterates through each element in the array, and results in the outputting of the following text:

Amos gets a A<br />
Jack gets a A<br />
Susan gets a B<br />
Donny gets a C<br />
...

… and so on.

Looping through multidimensional arrays

When dealing with multidimensional arrays, as we have seen, it is often the case that you have a list of associative arrays within a simple array.

When this is the case, such as with the array of symphonies in the examples above, we can use the following code to loop through and output contents of the multidimensional array:

foreach ($symphonies as $symphony) {
 echo $symphony["composer"] . " composed " . $symphony["title"] . " in " . $symphony["year"] . "<br />";
}

This code iterates through each element in the $symphonies multidimensional array, and puts the value of each element into a variable called $symphony.  Recall that each element of the $symphonies array is actually an array in its own right.  So for each iteration of the loop, the $symphony variable holds an associative array containing just the data for that particular symphony.

We can then access the values held within this $symphony array the same way we access values held within any associative array: by using the proper keys.  The end result is the output of text like this:

Jean Sibelius composed Symphony #1 in 1898<br />
Richard Wagner composed Symphony in C major in 1832<br />
Ludwig van Beethoven composed Symphony #7 in 1811<br />

This technique of looping through multidimensional arrays will come in handy when we begin to deal with databases.

Class 7 – Assignment #1

Saturday, October 31st, 2009

Your in-class assignment today is to update your e-commerce pages from the previous class to be more “dynamic” and “templatized”.

Templatize the common sections of all pages in the entire site

Use separate PHP include files for the top ad banner, global navigation, breadcrumbs, skyscraper ad, and footer.  On a real site, these sections would be the more-or-less the same on all pages, so you would want to have them stored in reusable files.  These files will be included into the main XHTML file for each page using the include() function of PHP.  Feel free to check out the include examples that are up on the server.

Note: As a convention in this class, whenever you create a file that has a snippet of XHTML that is included into another page but never displayed directly on its own, I would like you to give it a name prefixed with the “_” character.  For example, the include files used in this assignment could be called:
  • _header.php
  • _breadcrumbs.php
  • _ad_banner.php
  • _ad_skyscraper.php
  • _footer.php
Templatizing these parts of the page will allow you to reuse those sections on multiple pages on your site, if you ever build it out to be more than one page, without having to rewrite the code for each.  Naming the files with this convention will make it obvious when looking at a list of your own files which ones are main XHTML pages and which ones are meant to be include files.

Templatize the products

Once you have finished that, it’s time to start templatizing the actual products that are displayed on the page as well.  This would, in theory, allow you to use the same page template for multiple categories of products.

We will do this in a different way than how we templatized the repeating sections of the page.  We will be using multidimensional arrays this time.  This exercise will be useful as a preparation for when we start to store data in databases.

Eventually, we will want the data for the products to be pulled from a database.  But for now, we’re just going to store data in an array as an intermediary step to that goal.

To templatize the products, create a PHP multidimensional array that contains all of your product data.  And use a PHP foreach loop to loop through that array and display the product data for each product on your page, rather than having it all hard-coded in the XHTML.

Do the tutorials, understand the examples

You are going to have to go through all the PHP tutorials on the Tizag site and my introduction to arrays in order to get a grasp of arrays and multidimensional arrays in particular.

Here is an example of how to get starting using a multidimensional array for this assignment.  I did not show how to use the foreach loop here, so you will have to investigate that, based on the example of looping through an array using the foreach command shown here.

Be sure to keep a backup of the work you did on the e-commerce page in previous classes – do not overwrite it, just make a copy of it.

Links to helpful documentation

Class 7 – Introduction to PHP

Saturday, October 31st, 2009

Today we enter the realm of server-side technologies.  PHP is the server side scripting language that we will be focusing on, but many of the high-level concepts we will be exploring with PHP could just as easily apply to other server-side languages like ASP.NET, Ruby, Python, Java Server Pages, and others.

What is PHP used for?

You may wonder why we even need server-side languages, given the we have seen how the vast majority of web pages are created with a combination of XHTML, CSS, and Javascript.  Use Firefox to View -> Page Source on any web page and you will probably see XHTML, CSS, and Javascript code, but absolutely no PHP.

Web developers use XHTML, CSS, and Javascript to control how content shows up in the web browser and how the user interacts with that content.  That’s the sole purpose of client-side technologies.   Server-side technologies, like PHP, are used to control how that content is assembled and managed on the server before it has even been sent to the browser.  Thus, PHP is used to dictate what is often referred to as the “business logic” of a web site.

There are three main uses of PHP:

  1. web page templating
  2. storing and retrieving content
  3. tracking user sessions

These three uses are not mutually-exclusive.  For example, templating and tracking users depends upon the ability of PHP to store and retrieve content.

Web page templating

Most web sites have elements of the page that are repeated on each page.  Very commonly, global navigation or other important navigation elements are repeated on all pages of a site.  For example, Google uses the same global navigation links across many of its sub-sites. Notice that the global navigation remains mostly the same from page-to-page, with slight changes:

Global navigation of Google home page

Global navigation of Google home page

Global navigation of Google home page with logged-in user

Global navigation of Google home page with logged-in user

Global navigation of Google Images with logged-in user

Global navigation of Google Images with logged-in user

Global navigation of Google News with logged-in user

Global navigation of Google News with logged-in user

It is very unlikely that Google engineers have hand-coded each of the pages on the Google site individually to have the same XHTML and CSS code for this top section.  If this were the case, and Google decided to make a slight change to the layout of this top navigation section, the engineers would have to go through the code of each one of the pages of all these Google sub-sites, and change the XHTML accordingly.  This would be a very inefficient and expensive way of maintaining a site.

It is much more likely that the engineers have coded this top section once, and are reusing that same code on each of the pages, with slight variations.  If they then wanted to make a change to this top section across the site, they would change that one bit of code, and the rest of the site would update automatically.  This would be referred to as being a template.

Take another look at the websites you frequently visit, and you will probably see that there are many sections of content that are repeated on each page.

Storing and retrieving content

When you visit many sites, you will see that the content is updated regularly but the design often does not change.  For example, news sites, e-commerce stores, and blogs all have regularly udpated content (news, products, and blog posts, respectively), while maintaining a consistent design.

Every time a new product is added to a store, the web developers do not usually have to hand-code the new product information.  Rather, they build a site that allows an administrator to enter the details of a new product into a form, and when they click submit, that information is stored in a database.  And each time a consumer visits the e-commerce site, the server-side code retrieves the latest list of products from the database and fits them into a web template.

As an example, consider the products on Amazon.com.  The listings of Sheets and the listings of Comforters look identical in layout and design, however the products that are listed in those two sections are different.  This is because the data is being pulled from two different data sets in a database – one for sheets, and one for comforters, but the data in each case is being fit into the same template.

Amazon.com Sheets

Amazon.com Sheets

Amazon.com Bedding

Amazon.com Comforters

Thus, the storage and retrieval of data is critical for any dynamic web site.  And this use of server-side scripting generally goes hand-in-hand with the templating of web pages.  In this case, the template would control the general layout and design of the products section of the site.

Data can be stored and retrieved to/from a variety of different places

  • databases, which store data in a way that is conceptually similar to spreadsheets
  • files, such as text or image files
  • web services, which are a mechanism that allows one server to store and retrieve data from another server
  • cookies, which are small bits of information that a server can store temporarily on the client computer

PHP can be used to handle the details of using each of these storage mechanisms.

Tracking user sessions

It is often desirable for a web site to be able to track visitors.  For example, a user who logs in to their webmail account expects to see their own mail and not someone else’s.  Thus, in order for the webmail web server to properly determine which user is currently using the site, it must track each visitor to the site in some way in order to differentiate between multiple users visiting the site at the same time.

Sometimes you want to track users even when they haven’t logged into your site.  For example, if you were giving a tutorial on your site, you may want to know how far each user has gotten in the tutorial, even without requiring them to log in.

Tracking users usually involves using cookies at the very least.  Often, it will also involve the other sorts of data storage as well.

Class 7 – PHP Variables, Functions, and Arrays

Sunday, July 19th, 2009

When we learned how to create and use Javascript variables, and Javascript functions, we were learning techniques that apply across many programming languages.  Fortunately, in this regard, Javascript and PHP are very similar, and we will not have to re-learn the theory of variables and functions.  We will just focus on the slight differences between the syntax of the two languages.

PHP variables

In PHP, variables are declared and defined like this:

$someVariable1 = 10;
$someVariable2 = "something";

Notice the dollar sign before the name of each variable – in PHP all variable names begin with the dollar sign.  Also notice that, like Javascript, all PHP instructions must end in a semi-colon.

Variables do not need to be explicitly declared in PHP. Whereas in Javascript, we declared variables, as in “var someVariable”, before using them, in PHP, we usually just define them.  PHP automatically handles the declaration.  There are some circumstances in which we may want to declare our intention to use a variable in PHP without actually giving it a defined value. Doing so is as simple as:

$someVariable1;

Like Javascript, PHP is a mostly untyped language, meaning a single type of variable can hold the any type of data: numeric values, Strings (i.e., text), arrays (i.e. lists), and other more complicated types of data (i.e. objects.)

PHP functions

Functions in PHP look almost identical to their Javascript counterparts.  A simple function definition might look like:

function doSomething() {
  echo "Hello World";
}

To call this function, one would use the following code:

doSomething();

This function would simply output the text “Hello World”.  “echo” is a special PHP command to output some text.

Parameters in functions must use the PHP syntax for variable names, meaning they must begin with a dollar sign.  For example, here is a function that accepts a parameter:

function sayHello($personName) {
  echo "Hello, " . $personName;
}

This function takes one parameter, which it calls $personName.  It then concatenates the text, “Hello, ” with the value of the variable $personName.  Unlike Javascript, PHP does not use the “+” sign to do string concatenation.  In PHP, “+” is used only for mathematical addition.  PHP uses the concatenation operator to concatenate strings.  So, for example, calling the function like this…

sayHello("Andy");

…would put the word, “Andy” in the variable called $personName.  The function then concatenates the text, “Hello, ” with the word “Andy”.  And ultimately, the function would output the following text:

Hello, Andy

PHP arrays

The built-in array() function of PHP is used to create arrays.  Recall that arrays are lists of things, not single values like regular variables.

To create an empty array which can be populated with data later in the code, call the array() function with no parameters.

$arrSomething = array();

To add an element to the array at index 15, use code such as:

$arrSomething[15] = "the sixteenth value in the array";

To add an element to the array at the next available index, simply leave the index blank, as in  the following code:

$arrSomething[] = "the new value";

To output the value of the 16th item in the array (remember that arrays are indexed starting from number 0, so the 16th item actually has an index value of 15):

echo $arrSomething[15];

In our example, that statement will output the following text, since that is what we stored earlier at index 15 of the array:

the sixteenth value in the array

PHP associative arrays

PHP arrays, like Javascript arrays, can be indexed by either integers or Strings.  When they are indexed by Strings, they are often called “associative arrays”.  To create an element in an array indexed by a String, use code like this:

$arrSomething["my_birthday"] = "October 3".

To output the value of this item of the array later in the code:

echo $arrSomething["my_birthday"];

This will output the following text:

October 3

PHP multidimensional arrays

PHP, being a loosely-typed language, allows you to put anything you want into a variable.  Variables can contain numbers, strings, objects, or any other data type.  Arrays are the same.  Array elements can hold numbers, strings, objects, and other data types including other arrays.

$myArray = array();
$myArray[] = 100; //array element 0 holds the number 100
$myArray[] = "some text"; // array element 1 now holds the string, "some text"
$myArray[] = array(); //array element 2 now holds an empty array
$myArray[] = array("this", "that", "the other"); //array element 3 now holds an array with three elements in it

echo $myArray[0]; //outputs the number, 100
echo $myArray[1]; //outputs the text, "some text"
echo $myArray[2]; //outputs the text, "Array"... this is probably not what you wanted.
echo $myArray[3]; //outputs the text, "Array"... this is probably not what you wanted.
echo $myArray[3][0]; //outputs the text, "this"
echo $myArray[3][1]; //outputs the text, "that"
echo $myArray[3][2]; //outputs the text, "the other"

Class 7 – The Main Uses of PHP: Templating and Business Logic

Sunday, July 19th, 2009

PHP is the server-side programming language we will use for the remainder of this course.  PHP is a general-purpose language that can be used for many things.  However, parts of the language have been especially designed to be easy-to-use in web development.  The primary uses of PHP in web development are:

  • templating
  • business logic

Templating

Templating is the process of distilling the component parts of a web page, or a set of web pages, such that there is as little redundancy between pages as possible.  This is easily illustrated with an example.

The BBC News website uses the same header section on every single page:

BBC News header

BBC News header

Every page on the BBC News site also has the exact same left navigation section:

BBC News left navigation

BBC News left navigation

… and every page on the BBC News site has the same footer at the bottom:

BBC News footer

BBC News footer

Given that there are thousands of pages within the BBC News website, if the website managers decided to add a new featured link to the header, they might have to modify the top section on 10,000 seperate XHTML pages.  Clearly, this can become unmanageable, even for a much smaller site.

Any web developer with a modicum of experience would immediately realize that a site such as this should be broken down into templates.  Most likely, the XHTML code for the top header section is stored in its own file, isolated from the rest of the page.  Let’s say this file is called “_header.html”.  Every page on the site includes “_header.html” into the top section of the XHTML for that individual page.  If the site administrators want to add a new link to the top header, then they edit only “_header.html”, and all the pages on the site automatically show that update, since they are all loading the header XHTML code from that file.

The same process would occur for the left navigation section, footer, and any other elements that repeat themselves across the site.

Business logic

The second most important use of PHP is to implement what is called “business logic.”  This consists of the logical rules necessary to determine what content should be shown on any given page.

For example, when a user goes to bing.com, and enters a search term in the form, you know enough to realize that this is probably an XHTML page with CSS style sheets, and a <form> tag with a <input type=”text” …> text input where users enter in the term they want to search.  When you type a search term into this form, such as “web development intensive”, and click submit, you are taken to a new page with the search results.  Somehow, this new page knows what you typed in the form on the last page, and has gone and retrieved a list of sites that match the search term “web development intensive”, presumably from a giant directory of websites somewhere.

The search results page is presumably templated.  Each search result page looks pretty much the same.  The header, footer, left nav, and right nav sections of the page look pretty much the same no matter what you search for.  It’s really just the exact details of the search results that differ from one search to the next.  It’s safe to assume that this page is templated, and the details of exactly what search results are shown on any given search results page are dictated by certain business rules.  The logical rules determine what content gets put into the template.

This page has used business logic rules to infer what it was you wanted to do on this site, and has retrieved the relevant content from a database somewhere and shown you the search results in well-formatted (presumably templated) XHTML code.  Any e-commerce site, news site, search engine, classifieds site, or any other type of site with dynamic content that is stored in a database will most likely operate the same way.

Class 7 – Working With Comma-Delimited Text Files

Saturday, April 4th, 2009

As a hint for your advanced assignment, here is an example of working with comma-delimited text files.  I have taken the example of a text file that has three fields for each line: image_path, caption, and username.  So the text file is structured something like this:

files/image1.jpg,this is the caption for the first image,amos
files/image2.jpg,this is the caption for the second image,amos
files/image3.jpg,this is the caption for the third image,amos

Where each line of the text file has those three fields separated by commas.

The file, index.php, compiles an array that contains the data for each line of the text file.  It then loops through this array and outputs each field of each line of text into an XHTML table tag so you can see it on the page.

The add_image.php, and process_add_image.php scripts write new data to the text file.  They assemble a line of text with three fields broken up by commas, and then write that line to the text file.  Once the line has been written, the user is redirected to the index.php page.

Class 7 – Advanced Homework Assignment (optional)

Saturday, March 28th, 2009

If you are finished with the in-class assignment, and you feel comfortable with the material in the tutorials, here is an optional advanced assignment to keep you busy:  convert the in-class assignment so that the product info is being pulled from an external plain-text file into a PHP multidimensional array.

You will have to modify your code so that the product info is no longer hard-coded in the PHP script, but the basic structure of how you loop through the multidimensional array should remain the same.

You may want to peek into the file_readwrite/read.php script on the server, which shows how to read line by line out of a text file.

I suggest that each line in your text file use delimiters, like commas, to separate the various fields of data that you’re storing.  So the contents of each line in this text file would hold all the fields necessary for one product.  The fields might look something like:

<product_id>,<product title>,<product description>,<product_link>,<product_price>

So, for example:

1,Big Cookie,This is a really big cookie, http://onepotcooking.com/somefile,$99.00

You may find the PHP built-in implode() and explode() functions to be useful for dealing with string delimiters, such as the comma in this case.

You’ll want to pay attention to the PHP – File Read pages in the tutorials as general info for dealing with files.

Class 7 – Basic PHP Example Links

Saturday, March 28th, 2009

BASIC SYNTAX

ECHO EXAMPLES

INCLUDE FILES

REDIRECTING TO ANOTHER PAGE

GETTING INFORMATION ABOUT YOUR PHP SERVER SETUP

STRING MANIPULATION