Posted: April 28th, 2009 | Author: amos | Filed under: cms, e-commerce, information architecture | Tags: class 10 | No Comments »
The fundamental concepts of e-commerce are easy enough to grasp, and these days most e-commerce sites follow normative standards and conventions. There are three basic components: the store-front, the shopping cart, and the checkout.
In this post, I’ll discuss each of these components. How these components are implemented in code depends, like many advanced topics, on what framework you’re working with, what language, and the style of development you or your team have.
The Store-front
When someone is shopping on the web, they want to browse products on a site to see what’s available. The listing of how products are displayed on your site is termed the “store-front”.
Usually, products use categorization to make it easy for users to find the sort of products they’re looking for. If you remember from way back when, we discussed the elements of navigation that an information architect should be aware of when organizing the content of a site.
In terms of information architecture…
A shoe store typically has top-level categories such as Men’s and Women’s. A shoe store might also have one or more levels of sub-categories of each top-level category. For example, the Men’s category might have sub-categories such as Boots, Sandals, Dress Shoes, Sneakers etc. It is not uncommon for a particular product to fall into more than one category. For example, a casual hiking boot may fall under both Hiking and Casual. You may also want to add the ability for visitors of your hypothetical shoe store to search products by facets, including price, color, brand, specials, etc.
Managing the store-front of an e-commerce site is a matter of organizing products, and managing inventory. How you organize the store-front, and how you categorize your products, are important concepts to work out in the information architecture phase of an e-commerce project, since the methods of navigation and categorization that you choose will affect every aspect of the site architecture.
In terms of development…
A store-front, if you were to build one yourself, would most likely have separate database tables for categories, products, and the association of products to categories. All the data about categories and products would then be read from the database. Store-fronts must also begin a “session“, which automatically assigns a session id to the user and stores it in a cookie. This is important so that the server can track each user and make sure that one user’s shopping cart is not confused with another user’s shopping cart, even if the user’s are not registered with the site.
A typical categories table might have fields for id, title, parent_category_id, and created. A products table would typically have fields for id, title, description, num_available, price, thumbnail_image_path, large_image_path, and created. An association table could have fields for id, product_id, category_id, created, thereby allowing for a many to many relationship between products and categories by thereby having a separate row for each category a particular product belongs to.
The Shopping Cart
Shopping carts are an essential part of any e-commerce site. They take the metaphor of the physical shopping basket, and transpose it into online media. At its most fundamental, a shopping cart is tool for maintaining state and remembering which products a user has selected for purchase so that they can buy them all together as a batch without having to re-enter their billing and shipping info for each one individually.
In terms of development…
As you can probably imagine, most shopping carts are simply tables in a database that have fields for user_id, product_id, and quantity (as well as the id and created fields, of course). That way, the database table simply has a row for every product in the user’s cart. To get the contents of the cart, you make a query on the table for all rows that match a given user_id.
It may be that you want to allow non-registered users to also add items to a shopping cart. In this case, you wouldn’t be able to store their user_id in a database since they do not have a user_id. There are two ways to get around this problem: either you store the items in their cart as data in a cookie (stored on their client machines) instead of in the database, or you can add a temporary shopping cart table to the database that associates items with a user’s session_id rather than their user_id. Remember that session_ids are automatically assigned by PHP’s Sessions functionality, and do not require users to register. The temporary shopping cart table might be called, “temp_cart”. It might have fields for id, session_id, product_id, quantity, and created.
Payment Processing
The checkout and payment processing parts of an e-commerce site are the most complicated. You need to securely process a transaction on a user’s credit card. This entire process should take place on a secure server where all communication between the client and server is encrypted.
To have a merchant account or not to have a merchant account?
In order to process credit cards online, you need to have what is known as a merchant account with a bank. To charge cards over the phone, in a store, or online, merchants need these special accounts with a bank. If you do not have a merchant account with a bank, you will need to use a payment processing service like PayPal or Google Checkout, which does not require you to have your own merchant account setup. PayPal uses its own merchant account to process your payment (and of course they charge an extra fee for this.) This is why PayPal is so popular with small merchants.
Assuming you have a merchant account (or are using a payment service that does), the first step in processing payment online is to send the data of what items are in a user’s shopping cart to a script that then calculates the total fee owed, as well as an taxes and surcharges. So the first step is a transfer of information from the shopping cart to the payment processing service. Once the user enters his/her credit card, billing, and shipping info in the payment processing step, you perform a transaction on their credit card by first authorizing it with the issuing credit card company.
If the credit card authorization passes, you must process the order with the credit card company by charging their card, remove the items from the user’s shopping cart, and make sure your site’s product inventory (the num_available field in the products table) is up-to-date now that you have sold off a few items. Once everything is finished, you show a confirmation screen to the user with an order receipt. Often, the site will automatically send an email to the user (assuming they entered an email address) with the order receipt in it.
One rule of thumb to follow if you are running your own store is never store sensitive information like credit card numbers in your database. Unless you have a budget to hire a good security expert, your site can be (and very well may be) hacked, and you do not want to be liable for the damages that would result from someone getting a hold on your clients’ credit card numbers.
Due to the complication of doing all these steps yourself, most online merchants opt to use a third-party payment processing service, such as Authorize.net or PayPal, that provides security and handles all the dirty work of charging a card for them. I recommend you do the same.
Conclusion
The components of an e-commerce site are really just a new combination of the techniques and technologies you are already familiar with. However, given the amount of work it takes to get all the interaction between the parts working correctly, it can be very time consuming to set up. Also, given how important it is that you do not make mistakes or errors in any of the steps, the risk associated with developing a homemade shopping cart is pretty high.
For these reasons, I recommend you use a 3rd party content management system (CMS) to do as much of this work for you as possible. A popular 3rd party library or CMS should be well-tested, secure, easy for you to integrate with your site, and easy for the user to navigate. So when you are evaluating 3rd party tools, bear each of these issues in mind. Also determine whether the software handles all of the store-front, shopping cart, and payment processing, or only some of those parts.
There are a variety of e-commerce “solutions” that handle some or all of the components of e-commerce mentioned above.
Simple e-commerce shopping cart solutions include:
Popular solutions for both the store-front and shopping cart include the following content management systems:
- LemonStand – an e-commerce CMS. This is a commercial product.
- X-Cart – an open-source, free e-commerce CMS. Handles the store-front and shopping cart; is built to integrate with the popular payment processing services, such as PayPal or Authorize.net.
- Zen Cart -an open-source, free e-commerce CMS. Handles the store-front and shopping cart; is built to integrate with the popular payment processing services, such as PayPal or Authorize.net.
- Magento – an e-commerce CMS. Handles the store-front and shopping cart; is built to integrate with the popular payment processing services, such as PayPal or Authorize.net.
Popular payment processing solutions include:
- PayPal Payment Processing – handles just the payment processing part. Does not require you to have a merchant account with a bank. Assumes you already have a store-front and shopping cart in place.
- Authorize.net Payment Processing – handles just the payment processing part. Requires you have a merchant account with a bank. Assumes you already have a store-front and shopping cart in place.
In addition to these stand-alone solutions, there are a variety of WordPress plug-ins that add store-front and shopping-cart functionality to a WordPress site. Some popular ones include:
- WordPress e-Commerce – a WordPress plugin that adds store-front, shopping cart, and integration with payment processing services
- Shopp - a WordPress plugin that adds store-front, shopping cart, and integration with payment processing services
These are just the one’s I have heard of recently. You will find that there are dozens of PHP-based e-commerce solutions available with just a simple search.
Posted: April 27th, 2009 | Author: amos | Filed under: rss, xml | Tags: class 11 | No Comments »
XML, as you probably have gathered by now, is a generic markup language that is used to structure data in a way that is easily-readable by humans, and easily parseable by computers. The average web developer doesn’t usually deal with XML. But depending on your proclivities, you may find it interesting. If you do, here is a simple starting point for how to think about it.
XHTML, RSS, and OPML are all subsets of XML, the general language that represents data as a series of nodes. I will use the terms “tag”, “node”, and “element” to be synonymous, although as far as the XML specification goes there are minor differences between the three which are mostly irrelevant to us at the moment. For now, think of a node as a tag, and a tag as a node, and a tag as an element, and an element as a node.
You are already familiar with the general way that XML tags are written, given that you know XHTML. The difference is that XHTML has prescribed set of tags that you can use. XML stands for extensible markup language, which means that in XML you can use whatever tag names you want… it’s up to you to decide what tags to use, and what they mean.
XML syntax rules
There are only a few rules for how to structure XML documents that you should be aware of if you ever work with XML. There is plenty of documentation available online about the syntax of XML, so here is a quick overview of the most important parts:
- The first line in the document must be the xml tag: <?xml version=”1.0″ encoding=”UTF-8″?>
- There must be one root node that contains all other nodes. In the case of XHTML, this will be the <html> node, for RSS it is the <rss> node. For your own custom XML formats, you can call it whatever you want, so long as it surrounds every other tag in the document.
- XML is case-sensitive. So as a general convention, to keep things simple, I recommend you always use lowercase letters.
An example of an XML document
Here is a simple example of an XML document that represents the list of students in a class:
<?xml version="1.0" encoding="UTF-8"?>
<class>
<title>Web Development Intensive</title>
<description>A course about the making websites</description>
<instructor>Bob Shakey</instructor>
<students>
<student>
<first_name>John</first_name>
<last_name>Smith</last_name>
</student>
<student>
<first_name>Mary</first_name>
<last_name>Wahloo</last_name>
</student>
<student>
<first_name>Dmitry</first_name>
<last_name>Johnson</last_name>
</student>
</students>
</class>
You can see a few things about how I have decided to structure this example:
- it is written in plain text – all XML documents are just plain text documents
- the first line is the xml tag, which indicates what version of XML we are using – all XML documents must have the xml tag in the first line
- all tags are lowercase – this is my choice
- there is a root element that contains all other elements – all XML documents must have a root element
- the root element is called <class> – this name and all the other names of elements are words I made up
- elements are be nested, one inside of another. And this nesting is not arbitrary.
- the elements nested inside of the <class> element hold information about that class
- and the element <students> surrounds a list of <student> elements that contain information about each student
XML namespaces
It is possible, with XML, to use namespaces to indicate more information about what set of rules any particular tag should follow. Looking at an example will make this clearer.
Take the hypothetical scenario where there are two different kinds of students who can take classes: students who come from Pratt, and students who come from NYU. And the data about each student comes from two different places: NYU student data comes from an NYU database, and Pratt student data comes from a Pratt database.
You have seen in my class list example above that I am using a tag called <student> that contains info about a student. With namespaces, it’s possible for me to have two versions of the <student> element: one for Pratt students, and another for NYU students.
<nyu:student>
<nyu:first_name>John</nyu:first_name>
<nyu:last_name>Smith</nyu:last_name>
</nyu:student>
<pratt:student>
<nyu:first_name>Mary</nyu:first_name>
<nyu:last_name>Wahloo</nyu:last_name>
</pratt:student>
<nyu:student>
<nyu:first_name>Dmitry</nyu:first_name>
<nyu:last_name>Johnson</nyu:last_name>
</nyu:student>
An XML parser, which understands the rules of XML and knows how to properly read data represented in XML format, will see these two types of “student” tags as two totally separate tag names with no relation to each other.
In fact, each namespace, “nyu” and “pratt”, is usually defined in a definition file, which contains instructions on what tag names and nesting structures are allowed for tags within that namespace. When using a namespace, you must indicate in the XML document a URL to a namespace definition document where these namespace rules are defined.
So, our updated example with namespaces would look like this:
<?xml version="1.0" encoding="UTF-8"?>
<class
xmlns:nyu="http://nyu.edu/some_imaginary_namespace_definition_file.xml"
xmlns:pratt="http://pratt.edu/some_imaginary_namespace_definition_file.xml">
<title>Web Development Intensive</title>
<description>A course about the making websites</description>
<instructor>Bob Shakey</instructor>
<students>
<nyu:student>
<nyu:first_name>John</nyu:first_name>
<nyu:last_name>Smith</nyu:last_name>
</nyu:student>
<pratt:student>
<nyu:first_name>Mary</nyu:first_name>
<nyu:last_name>Wahloo</nyu:last_name>
</pratt:student>
<nyu:student>
<nyu:first_name>Dmitry</nyu:first_name>
<nyu:last_name>Johnson</nyu:last_name>
</nyu:student>
</students>
</class>
Note the two new attributes of the <class> element:
- xmlns:nyu indicates a URL where the “nyu” namespace is defined
- xmlns:pratt defines a URL where the “pratt” namespace is defined
In practice, it is not uncommon for these to be fake URLs that don’t actually point to any definition document. The XML parser will never actually check to make sure that the URLs really contain definition files. These URLs are there more for the humans who happen to read the code.
So for most small to medium-sized projects, you are usually free to use XML as you wish, without worrying about definition files, so long as you declare the namespaces you are using with fake URLs.
On large-scale projects, you will probably want to actually create real definition files to make sure you are complying with whatever namespace specifications you have decided upon for your set of possible XML elements and nesting structures. On large-scale projects, more strict coding standards are usually beneficial to keeping the project from getting too inconsistent and difficult to manage.
Taking a look at RSS as XML
As we know, RSS is a subset of XML, meaning it follows all the rules of XML. There are actually several different specifications which people generally refer to as simply “RSS”: RDF, RSS 2, and Atom, and others. Each specification contains a list of tag names, rules for nesting those tags, and what those tags are supposed to mean. In other words, they are more-or-less namespace specifications.
For almost all the intents and purposes of the average developer, all the competing RSS specifications are equivalent, and don’t listen to anyone who tells you otherwise. Unless you have a very specific reason for picking any particular one, you can just choose one type arbitrarily. Any decent RSS reader, like Google Reader, will be able to deal equally well with any of these types.
Let’s take a look at the RSS that the class blog publishes. To see this RSS feed live on the site, go to the class blog in Firefox at http://wd.onepotcooking.com, click the RSS icon in the address bar of the browser:

RSS icon
and then click “View Source”.
You should see RSS code like this, but with more than one “item” element:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
>
<channel>
<title>Web Development Intensive</title>
<atom:link href="http://wd.onepotcooking.com/?feed=rss2" rel="self" type="application/rss+xml" />
<link>http://wd.onepotcooking.com</link>
<description>NYU SCPS</description>
<pubDate>Mon, 27 Apr 2009 01:57:40 +0000</pubDate>
<generator>http://wordpress.org/?v=2.7</generator>
<language>en</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<item>
<title>Class 10 - An MVC Social Network Example</title>
<link>http://wd.onepotcooking.com/?p=480</link>
<comments>http://wd.onepotcooking.com/?p=480#comments</comments>
<pubDate>Mon, 27 Apr 2009 01:57:26 +0000</pubDate>
<dc:creator>amos</dc:creator>
<category><![CDATA[mysql]]></category>
<category><![CDATA[php]]></category>
<category><![CDATA[xhtml]]></category>
<guid isPermaLink="false">http://wd.onepotcooking.com/?p=480</guid>
<description>
<![CDATA[
this is where a short description of the blog post goes
]]>
</description>
<content:encoded>
<![CDATA[
this is where the full content of the blog post goes
]]>
</content:encoded>
<wfw:commentRss>http://wd.onepotcooking.com/?feed=rss2&p=480</wfw:commentRss>
</item>
</channel>
</rss>
A few initial observations:
- The document begins with an “xml” tag.
- You can see that the <rss> tag is the root node of the XML document.
- The <rss> tag defines a bunch of namespaces for tag names that are specified in the “content”, “wfw”, “dc”, “atom”, and “sy” namespaces, rather than in the RSS 2.0 specification itself that is the default specification used for this page. Try going to those URLs directly in the browser to see what these namespace specifications look like.
- The <channel> element has basic info about this site
- An <item> element is used to hold the contents of each blog post on the site.
- Some tags have a namespace prefix, and some don’t. Those without a namespace prefix are part of the RSS 2.0 specification, which is the default for this document. Those with a namespace prefix indicate that they are defined in another specification with its own set of tag names. So it’s clearly possible to use tags from a variety of specifications so long as the tags themselves indiciate the specification in which they are defined by using a namespace prefix.
- You see that the contents of some elements are wrapped in <![CDATA[...]]> tags. CDATA tags are used to indicate to any XML parser reading the contents of this document (in this case it would be an RSS reader), that it should ignore any special characters or XML syntax errors contained in the data within. For example, the contents of the <content:encoded> element are the actually contents of the blog post I wrote. I may have made some mistakes in my example code, and my blog posts may therefore have badly formatted XML, or XHTML that I wrote. Putting that data inside the CDATA tag in the XML tells the RSS reader, which would normally throw an error when it encounters badly formatted XML, that it should not try to evaluate whatever is inside that tag as valid XML. So it just ignores it, and treats it as plain text.
I recommend, if you’re interested in this, that you go to multiple news sites and blogs, and click the RSS icon in the address bar, and view the source code of their RSS feeds. You will get a good idea of how commercial sites are structuring their RSS code. Given that RSS is still a new technology that doesn’t always adhere perfectly to the standards defined in the various specifications, the best guide you can have for how you should structure your RSS code is to look at other feeds from the major blog and news companies and follow their example.
Posted: April 26th, 2009 | Author: amos | Filed under: php | Tags: class 9, controller, model, mvc, view | No Comments »
MVC architecture is a growing trend in software development of all kinds, including for the web. If you can master object-oriented programming combined with MVC architecture, you can consider yourself to be a very knowledgeable developer.
This architecture divides the code involved in any project into three parts: Model, View, and Controller. It’s important to bear in mind that the idea of dividing a project into these three parts is a concept. How that concept should actually be implemented in practice depends on who you’re talking to, what language(s) you are programming in, as well as the framework you are using, if any.
M is for Model, V is for View, and C is for Controller.
The Model is the part of the code that deals directly with the database. So all the code that does the database CRUD (create, read, update, delete) functions, as well as any other code that makes direct queries to the database should be considered part of the Model. Any time any code in any application you are building needs to interact with the database in any way, it has to do that by calling functions in the Model.
The View is the part of the code that creates the interface that the user sees. For web development, the View consists mostly of the XHTML, CSS, Javascript, and any other client-side technologies that create the actual interface of the web site. The view is the sort-of template that is then filled in with data that comes from the Model.
The Controller is the sort of brains of the operation. It is the glue that links the Model, the View, and the user together. The controller’s main function is to figure out what the user is trying to do, and to then use the Model to get the data that is necessary to do that, and then use the View to display that data to the user in a nicely designed page.
Posted: April 25th, 2009 | Author: amos | Filed under: php, rss | Tags: class 10 | No Comments »
In class today, we’re looking at an example of how you can use the SimplePie PHP library to pull content from any site’s RSS feed and display it on your own pages.
In this example, SimplePie is acting as the Model in an MVC architecture. index.php is the Controller, and index_view.php is the View.
In the example files, you will notice that there is a folder called “cache”. This is where SimplePie temporarily stores copies of the RSS feeds that you load. It keeps each cached copy of the RSS feed for several minutes, so that if you reload your page, it doesn’t have to always reload the same data from the site that publishes the RSS feed.
In fact, some sites will ban your site from accessing their RSS feeds forever unless you store cached copies of their feeds. This is because they want to minimize the number of requests that are made to their servers. SimplePie does this by default if you have a “cache” folder available.
You’ll also notice an “images” folder. This stores default placeholder images for media files. SimplePie integrates with the JW Media Player application. So if a particular RSS feed has media attachments, whether audio or video, SimplePie will automatically generate the appropriate JW Media Player code, so you don’t have to worry about doing it yourself.
If you use SimplePie, you will need to make sure you have the simplepie.inc file (which holds the main SimplePie code), the cache folder (which stores cached copies of all RSS feeds), the images folder with default images, and the idn folder (which holds other misc SimplePie files).
Posted: April 24th, 2009 | Author: amos | Filed under: javascript, xhtml | Tags: class 10 | No Comments »
To play audio or video files on a web page consistently across all the browsers, you will want to use a Flash media player. Adobe Flash is the most widely supported application on the web for playing audio and video files. As we mentioned early in the course, Flash is also commonly used to do animation on the web.
There are a variety of Flash media players available online, some free, some not. One of the most common, and easiest to use, is the freely available JW FLV Media Player. The nice thing about the JW FLV Media Player, and other players of its ilk, is that you can relatively easily skin it to make it fit the design of your site.
The bare bones approach
Note: While the following is the simplest way to put a Flash application on your page, and it is worth understanding, it is not the recommended approach. Skip below for the recommended approach.
To place any Flash application on your web page using simple XHTML, you will need to use either the <object> tag, or the <embed> tags in XHTML. Historically, the <object> tag was used for Internet Explorer, and the embed tag was used for the other browsers. However, these days, <embed> is not considered to be valid XHTML, and it is no longer recommended for use. However, most modern browsers continue to support it.
The FLV Media Player apploication we will be using to play media files can be put on a page using the following embed code:
<embed
src="mediaplayer.swf"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
quality="high"
wmode="transparent"
flashvars="file=http%3A%2F%2Fwww.mos.org%2Fmedia%2Faudio%2F081121MOS_CSTPodcastTMGrapheneDDEelsX.mp3%3Ffile_extension%3D.mp3&autostart=false&repeat=false&showdigits=true&showfsbutton=false"
width="100%"
height="20"
/>
The “src” attribute tells the embed tag where to locate the flash media player file. Obviously, you need to make sure you have a copy of mediaplayer.swf in your own directories in order for this to work.
We then pass a parameter to this media player that indicates which media file it should play. The path to this media file goes inside the “flashvars” attribute. Notice that in this example, in the “flashvars” attribute, we are telling the media player to load a media file from another server. We could just as easily load a media file on our own server using a relative path instead of an absolute path. Also notice that the path to the media file is urlencoded.
To see this example in action on our server, click here.
The recommended approach
This example is the same as the first example above, but it uses the Javascript SWFObject.js library to put the Flash player on the page instead of using the <embed> tag. The SWFObject.js library is just a bit of code that creates the embed tag in Javascript and then places it on the page without you having to write it in XHTML. You’re probably wondering why you would want to use it…
This page gives a good overview of the two methods, the problems with the XHTML version, and the reasons for using the Javascript version rather than the XHTML version.
The code requires that you have downloaded the swfobject.js script, and have put it in a subfolder called “scripts” on your server. Once you have the file uploaded, you can included it into your XHTML file in the head of the document:
<head>
...the usual stuff in the head
<script type="text/javascript" src="scripts/swfobject.js"></script>
</head>
Once that’s taken care of, you put the JW FLV Media Player onto your page using this example code:
<script type="text/javascript">
var so = new SWFObject('mediaplayer.swf','mpl','100%','20','9');
so.addParam('flashvars','file=http%3A%2F%2Fwww.mos.org%2Fmedia%2Faudio%2F081121MOS_CSTPodcastTMGrapheneDDEelsX.mp3&autostart=true');
so.write('flashplayer');
</script>
Notice that the parameters are basically the same as we saw in the <embed> example: the location of the Flash application file, the width and height of the application, and the location of the media file that we want the media player to play. The difference, of course, is that these parameters are specified in Javascript.
PS: In case you didn’t notice, these parameters are obviously arguments being sent to the constructor function of an object in Javascript, similar to how we used constructor functions in object-oriented PHP.
Posted: April 23rd, 2009 | Author: amos | Filed under: mysql, php | Tags: class 10 | No Comments »
PHP debugging is an art-form. Here are some common tricks of the trade.
Indent your code properly
If you do not properly indent your code so that you can visually see the hierarchical relationships in it, you will never be able to successfully debug it. Furthermore, you will never become a successful developer. It’s that simple (almost). This applies to all XHTML, CSS, Javascript, and PHP code you will ever write.
Before you do anything else, indent your code. You will be amazed at how many errors you will see immediately.
The rule: Something that is “inside of” something else should be indented one level to the right. For example:
function doSomething($indented) {
$futureSuccess = false;
if ($indented) {
$futureSuccess = true;
}
return $futureSuccess;
}
Notice that all code “within” the function is indented to the right, relative to the opening and closing of the function. Further note that the code within the “if statement” is also indented one more level to the right. This makes the code easy to read, and so stupid errors, such as missing brackets, become easier to spot.
Foreach statement errors
If you encounter an error that looks like this, the problem is simple:

Let’s say your foreach statement looks like this:
foreach ($someArray as $someElement) {
///some stuff here
}
The error: This error is telling you that the variable $someArray is not actually an array. Don’t argue… PHP is always right about this.
The solution: make sure the variable you think is an array really is an array. You can see the contents of the array by printing out the raw contents of the array using the print_r() function like this:
print_r($someArray); //dump out the raw data in the array
foreach ($someArray as $someElement) {
///some stuff here
}
Hint: you can make sure your array is aways an array by declaring it as an array before you start using it.
$someArray = array(); //set the variable to a blank array
//do some stuff to put data into the array here
foreach ($someArray as $someElement) {
///some stuff here
}
This hint is especially useful if you are populating the array with data pulled from a database. For example, let’s say that you are running a query to load all of the comments for a blog post and put them into an array called $comments:
$result = mysql_query($myQuery); //run the query
while($row = mysql_fetch_array($result)) {
$comments[] = $row; //put the current row into the comments array
}
If, as is perfectly common, the blog post in question does not have any comments associated with it, the while loop will never loop, because there are no rows in the result variable. This means the $comments array will never have any data put into it, which is fine since there are no comments.
But if you later try to loop through all the elements in the comments array like this:
foreach ($comments as $comment) {
//do something
}
You will get this error because you have not said that $comments = array(); So make sure you always specify that an array is an array:
$comments = array(); //make this variable a blank array
$result = mysql_query($myQuery); //run the query
while($row = mysql_fetch_array($result)) {
$comments[] = $row; //put the current row into the comments array
}
Unexpected $end error
You will most likely come upon this error at some point:

This is equally simple. It means that you are missing an ending bracket on some block of code. For example:
while ($something == true) {
//do something
The error: If you do not have a closing “}” at the end of the while loop, it will cause this error. The same is true for closing brackets on any kind of block statement, like for loops, if statements, while loops, switch statements, function definitions, class definitions, etc. Anywhere you have an opening bracket, you must eventually have a closing bracket:
while ($something == true) {
//do something
}
Hint: By the way, this same error is produced if you are missing a closing heredoc tag, or if the heredoc tag is not all alone on a line with no spaces before or after it. Here is an example of a heredoc tag with some spaces on the same line as the END; tag: this will produce the error. The END; tag must be the only thing on the last line.
print <<<END
this is some text I want to print to the page
END;
Can’t connect to local MySQL server
If you see an error that looks like this, it means that your script did not successfully connect to the database:

First debugging step: First, make sure you are including the script that has all the database information in it at the top of your script:
//require database connection info
require_once("dbinfo/db.php");
Second debugging step: Make sure the db.php file has the correct username, password, hostname, and database name in it.
$dbServer = "mysql.fakedomain.com";
$dbUser = "amos";
$dbPass = "noneofyourbusiness!";
$dbName = "exampledb";
Third debugging step: Make sure that you are connecting to the database at the top of your script, and disconnecting at the bottom:
//require database connection info
require_once("dbinfo/db.php");
//connect to database
$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
//do something interesting
//disconnect from database
$cxn = @DisconnectFromDb($dbServer, $dbUser, $dbPass, $dbName);
MySQL query not working as expected
It happens every class that someone has a problem where the data they were expecting to store in the database does not seem to be getting stored there. Or the rows they were trying to read with a SELECT statement are not getting read. MySQL queries are extremely simple things to debug.
Let’s say you have a query statement like this, but it’s not working.
$myQuery = "INSERT into abloomberg_posts (user_id, title, body) VALUES ({$userId}, '{$title}', '{$body}')";
$result = mysql_query($result);
Before you start: Before you even bother debugging, you should have phpMyAdmin open in a browser tab so that you can easily browse the contents of the table you are trying to insert data into. Clicking the “Browse” tab in the “table view” for the table you are dealing with is easiest way of checking to see if data is getting stored in your table.
First MySQL debugging step: First, you want to make sure that the command to query the database is actually getting executed the way you think it is. Maybe the variables you are using, $title, and $body do not have what you think they have inside them. So add a little echo statement that outputs the query you are trying to run.
$myQuery = "INSERT into abloomberg_posts (user_id, title, body) VALUES ({$userId}, '{$title}', '{$body}')";
echo $myQuery;
$result = mysql_query($result);
You will be surprised at how often this simple echo statement will show you the problem. For example, if this code outputs something like the following:
INSERT into abloomberg_posts (user_id, title, body) VALUES (, '', 'this is the body')
That would indicate that the $userId and $title variables do not have anything in them, which is why they are showing up blank when you echo the query.
Second MySQL debugging step: the second easiest debugging step is to output any errors that MySQL is encountering. These won’t be output by defuault, so you must specify that you are interested in seeing them. Use the mysql_error() function after you run the query:
$myQuery = "INSERT into abloomberg_posts (user_id, title, body) VALUES ({$userId}, '{$title}', '{$body}')";
$result = mysql_query($result);
echo mysql_error(); //output any MySQL errors
If this produces an error on the page, it will indicate if your MySQL query syntax has something wrong with it. Check the syntax of the query you are running by echoing it as we did in the first step, and make sure it looks correct:
$myQuery = "INSERT into abloomberg_posts (user_id, title, body) VALUES ({$userId}, '{$title}', '{$body}')";
echo $myQuery . "<br />"; //echo the query to the page $result = mysql_query($result);
echo mysql_error() . "<br />"; //output any MySQL errors
Invalid MySQL result resource
If you see an error that looks like this, it means that you have done a query, but that something has gone wrong and that query hasn’t worked. So There is something wrong in the code where you say mysql_query()… So you have no results of the query to work with.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
Here’s an example of code which would trigger this error:
$query = "SELECT * from example_errors WHERE 1";
$result = mysql_query($myQuery);
while($row = mysql_fetch_array($result)) {
//some code here
}
Here you are saying mysql_query($myQuery). The $myQuery variable is undefined and does not contain any query. Your query is stored in the $query variable, no the $myQuery variable. So the $result variable ends up being invalid. So the mysql_fetch_array($result) command doesn’t work. So you get this error when you try your while loop.
Follow the same debugging procedures as for the MySQL query not working as expected, above.
Column not found
Create a custom error handler
It is possible to handle errors in a customized way. I do not recommend you do this in PHP, but I’m including it here to be thorough about the topic. Feel free to skip the rest of this blog post.
You can choose to ignore some errors and respond to others as you see fit. To do so, you will need to create an error handler. This is conceptually similar to how we created event handlers in Javascript to respond to onclick events, etc.
First of all, you must specify which errors you want to see using PHP’s built-in error_reporting() function. You can see the full list of possible errors on the PHP reference page for this function. Here are the most common ones you’ll be interested in:
error_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);
Then you specify which function gets called when an error of any of those types is encountered using the set_error_handler() function. This function takes one parameter: the name of the function that gets automatically called when an error occurs.
$errhandle = set_error_handler("myErrorHandler");
And of course, this means you must also define the function, in this case “myErrorHandler” that you specified just now. When an error occurs, this function will get called and automatically passed four parameters: the “error number”, the error message, the file that caused the error, and the line number in the code that produced the error. Here is a simple error handler that just detects which type of error occured, and outputs some text for each of them:
function myErrorHandler($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />n";
echo " Fatal error in line $errline of file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />n";
echo "Aborting...<br />n";
exit(1);
break;
case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />n";
break;
case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />n";
break;
default:
echo "Unkown error type: [$errno] $errstr<br />n";
break;
}
}
Suppressing errors
As an alternative, if you just wanted to suppress all errors, you could make a function like this instead:
function myErrorHandler($errno, $errstr, $errfile, $errline) {
//suppress all errors
return true;
}
And you can probably see that if you wanted to handle some types of errors in a custom way and you wanted to suppress others, you would create a function like the first example handler above, but “return true;” for those types of errors that you wanted to suppress.
Posted: April 18th, 2009 | Author: amos | Filed under: mysql, php | Tags: class 8 | No Comments »
When we set our MySQL tables to have a “created” field of the type TIMESTAMP with the CURRENT_TIMESTAMP option selected, this records the exact date and time that each row is created in the table.
The format that MySQL uses to record this data is “YYYY-MM-DD HH:MM:SS”. However, this is not usually the format that you want to use to display the data on the web page. It’s not so easy to read, and definitely is not how most people think of dates.
In order to convert the MySQL TIMESTAMP to a more user-friendly date format, you want to use PHP’s built-in date() function. However, PHP’s date() function only allows you to change the format of dates that are in Unix Timestamp, which is significantly different from MySQL’s TIMESTAMP format.
So, in order to get PHP’s date() function to work with MySQL’s TIMESTAMP, you first have to convert MySQL’s TIMESTAMP format to Unix Timestamp format. To do that, you use PHP’s strtotime() function.
Here’s the code that does this, from my blog example:
<p>posted <?php echo date("F j, Y, g:ia", strtotime($post['created'])) ?></p>
This displays on the page as, for example, “posted November 8, 2008, 12:19pm”. You can use the date() function to format the date in a wide variety of other formats.
The php.net reference page for the date() function has some easy examples somewhere halfway down the page.
Posted: April 18th, 2009 | Author: amos | Filed under: assignments, mysql, php | Tags: class 9 | No Comments »
Your assignment today is to complete a blog with comments. This should be based off of your assignments from last week, where you created a blog where users were required to register and login before they could post to the blog.
There will be changes to two pages in your blogs.
index.php
The home page will show all the blog posts, as well as all of the comments associated with each blog post. There will also be a link to “Add a comment” to any blog post.

Home Page
I recommend you study what I wrote about SELECT statements in an earlier post, especially the last bit about joining two tables together. It would be nice if you could join the users and posts tables together when doing a query for all the blog posts to show on the home page. This would allow you to get all the data about the post, as well as the data about the user who posted it in one fell swoop. Something like this:
$myQuery = "SELECT abloombert_posts.*, abloomberg_users.username FROM abloomberg_posts, abloomberg_users WHERE abloomberg_posts.user_id = abloomberg_users.id ORDER BY created DESC";
$result = mysql_query($myQuery); //run query
if ($result) {
//loop through each post
while ($row = mysql_fetch_array($result)) {
//get this post's id, title, body, and username of the user who posted
$userId = $row['user_id'];
$username = $row['username'];
$title = $row['title'];
$body = $row['body'];
$created = $row['created'];
//etc...
}
}
The link to “Add a comment” has to somehow pass the id of the blog post to which the comment should be associated to the comment.php script. This can be done by passing that data in the url of the link. For example
<a href="comment.php?post_id=<?php echo $postId ?>">Add a comment</a>
comment.php
The comment page will have a form that users can fill out to submit a comment. This page should show the user the title and author of the blog post they are about to comment on.

Comment Page
In other words, this page will have to take the post_id that was passed to it from index.php, and do a read from the posts database table to get the information for the post with that id.
You will probably use code similar to this:
$postId = $_REQUEST['post_id']; //get the post id that was passed from index.php
$myQuery = "SELECT * from posts where id={$postId}";
$result = mysql_query($myQuery);
//... loop through each row of the results and get the data about this post
The form where the user fills in the comment will also need to pass the post_id to the script that processes the comment so it can store the post_id in the comments table.
Assuming you have the blog post “id” field in a variable called $postId, the code for the form will probably look something like this:
<form action="process_comment.php">
<input type="hidden" name="post_id" value="<?php echo $postId ?>" />
<label for="comment">Comment:</label>
<textarea name="comment" id="comment"></textarea>
<input type="submit" value="Post Comment!" />
</form>
Notice the hidden input that has the value of the post’s “id” field. This means that when the user clicks the submit button, the form sends two pieces of data to the process_comment.php script: the post_id and the comment the user entered.
process_comment.php
The script that processes the comment the user entered must take the blog post id, the id of the current user, and the comment the user entered, and store this info in a new row in the “comments” table.
To get the necessary data, you will need to retrive it from the $_REQUEST and $_COOKIE variables. The post_id and comment will be in the $_REQUEST variable, and the user_id will be in the $_COOKIE variable, assuming you stored it in a cookie when the user logged in.
$userId = $_COOKIE['user_id'];
$comment = $_REQUEST['comment'];
$postId = $_REQUEST['post_id'];
So make sure you are storing the user’s id in a cookie when they login, or else this obviously won’t work.
Once you have that info, put together a SQL query that inserts this data into a new row in the “comments” table.
$myQuery = "INSERT INTO abloomberg_comments (user_id, post_id, comment) VALUES ({$userId}, {$postId}, '{$comment}')";
$result = mysql_query($myQuery); //run the query
Then redirect the user back to the home page.
header("Location: index.php");
Posted: April 16th, 2009 | Author: amos | Filed under: php | Tags: class 9 | No Comments »
Now that we’ve established what object-oriented programming is in theory, it will be useful to go through how this theoretical idea is actually implemented in PHP.
The skeleton of a class definition
The following is a bare-bones definition of a Dog class in PHP. This code would go into a file called Dog.class.php:
<?php
//file: Dog.class.php
class Dog {
public function __construct() {
}
}
?>
This class, as it currently stands, has no properties, no methods, and is basically useless. But it shows you the bare minimum amount of code necessary to define a class in PHP.
The __construct() method is a special type of method that is automatically called by PHP when an instance of the class is created. This is known as a “constructor function”, and is generally used to do some initial setup of the properties of the object that is being created.
For example, let’s say we have another script, index.php, which creates a Dog object:
<?
//file: index.php
require_once("Dog.class.php"); //include the Dog class definition file
$sparky = new Dog(); //create a new Dog object and store it in a variable
?>
When the script runs the “new Dog()” command, this tells PHP to create an object of type Dog. PHP creates this object, and then calls its __construct() method automatically.
Adding properties
Let’s now try to do some basic setup of the Dog object when it is created. Most likely, we would conceptually want to give the Dog a name at the time it is created.
To do this, we need to give the Dog class a “name” property, and then allow the constructor code to set that property to some value when the object is created.
Here is the updated Dog.class.php file:
<?php
//file: Dog.class.php
class Dog {
private $name;
public function __construct($dogName) {
$this->name = $dogName;
}
}
?>
The code to create a new Dog object would now look something like this:
<?
//file: index.php
require_once("Dog.class.php"); //include the Dog class definition file
$sparky = new Dog("Sparky"); //create a new Dog object and store it in a variable
?>
The first thing to note is the “private $dogName” code in the updated Dog class definition. This declares a “name” property of any Dog objects. Note that we define this property in the class definition file, but it actually comes into use for Dog objects created from that class. This is an important distinction: you define things in the class file that you intend to use for the objects created from that class. Sometimes these properties are called “instance variables” because they apply to all object instances of the specified class.
The keyword “private” indicates that any property or method will only be accessible to code within the class definition itself. Any code outside of this class definition will be ignorant of the existance of the “name” property of any Dog. This is an example of the concepts of abstraction and encapsulation: the inner workings of the Dog class can be hidden from world outside world.
The alternative is “public”, which we see being used in the constructor function, but can be used for any property or method that you want to make accessible to code outside of the class definition.
In index.php, we have supplied an argument to the constructor function by putting the word “Sparky” inside the parentheses of the “new Dog()” command. You’ll recognize that this is not so different from how we pass arguments to regular functions in PHP and Javascript.
PHP automatically calls the __construct() function when we declare “new Dog()”, and the constructor function now puts the word “Sparky” into the variable called $dogName.
The following line of code in the constructor function then modifies the $name property of the Dog object so that it too has the word “Sparky” in it:
$this->name = $dogName;
The $this keyword is a special variable that refers to the current object. It can only be used inside of a method in a class definition file. It refers to the current instance of the class. In this case, when the code is run, $this refers to the Dog object that we are calling “Sparky”, and not to any other Dog object that may exist at that time.
The syntax “$this->name” is how you would refer to the “name” property of the current object. You can use similar syntax for any property or method that is encapsulated inside of an object. For example, $this->doSomething() would call the doSomething() method of the $this object.
So we have effective created a Dog object, and set its name property to be “Sparky”. But what use is that?
Accessor methods
Obviously, you want to make it possible to use that “name” property in some way. Let’s say we want to be able to echo the name of the dog we created somewhere in our index.php script. We need a way to access this “name” property from outside of the class definition file.
But I’ve already said that the “name” property is “private”, and therefore not accessible to any scripts outside of the class definition file. So how do we access it?
The answer is that we have to create what are known as “accessor methods” for our class. By convention, an objects properties are not directly accessible to code outside of the class definition, so we supply public methods to get and set those property values (known sometimes as “getter and setter functions”.
Our updated Dog.class.php file will now look like this:
<?php
//file: Dog.class.php
class Dog {
private $name;
public function __construct($dogName) {
$this->setName($dogName);
}
public function getName() {
return $this->name;
}
public function setName($dogName) {
$this->name = $dogName;
}
}
?>
And our index.php file will echo out the dog’s name like this:
<?
//file: index.php
require_once("Dog.class.php"); //include the Dog class definition file
$sparky = new Dog("Sparky"); //create a new Dog object and store it in a variable
echo $sparky->getName();
?>
We have thus created accessor methods for the “name” property. These are two new public methods in the Dog.class.php file: one to set the “name” property of the Dog object, and another to get the “name” property of the Dog object. It is important that they are both “public”, so they can be called from index.php. And the “name” property itself is “private”, and therefore not directly accessible from the code in index.php.
Note that I have also updated the constructor function so that it too calls the setter method, rather than duplicating the same code found in that method.
The script in index.php now creates a new Dog object, and then outputs the name property of that object by calling its getter method.
Finishing the example
Now let’s finish this example by adding another property and a few new methods. We’ll add an “age” property, as well as the getter and setter methods for that property. We’ll also add a “bark()” method that will just output some text. And finally, we’ll add a static method, which we’ll discuss below.
Here’s the updated Dog.class.php:
<?php
//file: Dog.class.php
class Dog {
//declare private variables that will be accessible from scripts outside of this class
private $name;
private $age;
//function __construct is a "constructor function", which means it is called automatically when a new object is created
public function __construct($name) {
$this->name = $name;
}
//a function that tells the current Dog object to bark...
public function bark() {
echo "<p>{$this->name} says 'woof'</p>";
}
//this is a setter function - it allows you to set the value of a private property of the current object
public function setAge($dogAge) {
$this->age = $dogAge;
}
//this is a getter function - it allows you to get the value of a private property of the current object
public function getAge() {
return $this->age;
}
//example of a static function - these are not dependent on any particular instance of this class
//in fact you CANNOT use the variable $this in a static function, because there is not current object to refer to
public static function scratch() {
echo "<p>Oooo that feels good</p>";
}
} //end class
?>
And the updated code from index.php:
<?
//file: index.php
require_once("Dog.class.php"); //include the Dog class definition file
$sparky = new Dog("Sparky");
$sparky->setAge(5);
$petie = new Dog("Petie");
$petie->setAge(3);
$sparky->bark(); //call the bark function of the Dog, "Sparky"
$petie->bark(); //call the bark function of the Dog, "Petie"
//echo $sparky->getAge();
Dog::scratch(); //call the static "scratch" method of the Dog class
?>
This script now creates a Dog object and gives it the name “Sparky” and sets its age property to be 5. Then it creates a second Dog object, gives it the name “Petie”, and sets its age property to be 3.
The code then calls the bark() method of both Dog objects. Each Dog object will run its own bark() method. Each object will run this command:
echo "<p>{$this->name} says 'woof'</p>";
And since each object has a different value in the “name” instance variable, they will output different things. Sparky will echo “Sparky says woof”, while Petie will echo “Petie says woof”.
Static vs. instance methods
Finally, we call the static method scratch(). The syntax to call a static method is this:
Dog::scratch(); //call the static "scratch" method of the Dog class
The double colon, “::” indicates that the scratch() method is not a method of any particular Dog object (i.e., not an instance method), but is rather a method of the class itself. In otherwords, an object does not need to have been created in order to call this method.
We can call this method on a particular object, like we do with any other method of an object:
$sparky->scratch()
But the only reason to make a method static is so that we don’t have to have a particular object in order to call it. So we usually call static methods directly from the class itself instead:
Dog::scratch();
As we saw, Sparky’s bark() method does something slightly different from Petie’s bark() method. Static methods are called static because they are never dynamic like this, and they never refer to the properties of a particular object instance.
Whereas the processing of the bark() method depends on the $this->name property of the current object, static methods cannot ever use the $this keyword because they do not refer to any particular object at all. They are usually used for general utility methods that never need to change depending on context. Hence the keyword static.
A slight variation on this example code is available here.
Posted: April 11th, 2009 | Author: amos | Filed under: php | Tags: class 9 | No Comments »
In class today, we covered the basic concepts of object oriented coding in PHP. Many languages besides PHP allow you to write object-oriented code, and many people find it to be a more intuitive way of writing code than procedural code, which more or less what we have been doing up until now.
The core concept in object oriented programming is the relationship between a class and an object.
Classes
In object oriented programming, a class is an abstract concept of a thing. A Dog class, for example, would represent the concept “dog”, but not any particular instantiation of that concept.
All Dogs have certain features in common. They have a name, age, color, pedigree, etc. There are also actions that all dogs do, such as eat, sleep, bark, chew, pee.
In object oriented programming, we would make a Dog class and in that class we would specify a set of properties that all dogs have, and set of methods, which are the things all dogs can “do”.
In our example, our Dog class would have the following properties:
And the following methods:
Objects
Just as classes are abstract concepts of things, objects are concrete instantiations of those classes. So, if in our code, we would create objects out of classes.
If you wanted to create a specific instance of a Dog, say a dog called “Sparky”, you would create a Dog object out of the Dog class. That Dog object would then have all the properties and methods that are defined in the Dog class.
In code, you could then specify what the attributes of this specific instance of a Dog are. You could set the “name” property of the Dog object to be “Sparky”, set its “age” to be 10, for example. And you could, in code, tell the Sparky object to bark, chew, eat, or any other method that an instance of the Dog class is capable of doing.
You could create as many Dog objects as you wanted besides Sparky. They would all be created out of the same Dog class. The Dog class is like a mold out of which specific Dog objects are made.
Features of Object Oriented Design
There is plenty of documentation of object oriented design concepts online. Object oriented design offers specific features such as inheritance, abstraction, encapsulation, and polymorphism, which each offer specific advantages, and are intended to be used in specific ways.
Inheritance means that one class may inherit the properties and methods of another class. For example, a Australian Sheep Dog class and a Shiba Inu class may both inherit the same basic properties and methods described in a Dog class. We would say they were sub-classes that inherit from a Dog class. But they may also add more specific properties and methods that only apply to objects of their specific sub-class.
Abstraction means that how the class implements the various properties and methods is not important to usage of the class. For example, I could tell either an Australian Sheep Dog or a Cat to go to sleep, without worrying about how each of those classes implemented that behavior.
Encapsulation means that the specific methods and attributes that apply to one object may have the same name as the methods and attributes of another object, but they are specific to each object. So the methods and properties of Dogs are encapsulated within the Dog class, and are thereby separated from any methods and properties that apply to Cats, for example. Furthermore, the age property of Sparky is encapsulated with the Sparky object, while the age property of ChooChoo is encapsulated within the ChooChoo object, and is totally unrelated to Sparky’s age. Encapsulated data may be totally invisible to the outside world.
Polymorphism is the concept that many different kinds of objects (of different classes) may respond to the same sorts of instructions. For example, we can tell a Cat to scratch itself, and we can tell a Monkey to scratch itself. But how they do the scratching will be totally different. A Monkey will use its hands, while a Cat will use its back feet. The point is that many Classes may share a common set of commands to which they respond, but how they implement those commands may be totally different.