PHP ON A FAST TRACK

Companion web site: http://php.francik.name

BY J AROSLAW F RANCIK
VERSION 3.0 – OCTOBER 2011

Writing web based, database connected applications in PHP is not difficult, however many people get stuck on just the basic stuff, in the very beginning. Indeed, configuring the software, establishing the database connection and starting a simple server script may be troublesome for a not experienced user. This paper will guide you step by step to creating a very simple web application of a shopping cart, which may be a starting point for an on-line shop project. It will lead you from finding the basic tools (web server, php module, MySql database), through the set-up process, up to writing the code. One fundamental aspect of the development process in IT is that you will always have to face the fact that there will be problems. Problems are a natural part of your job, and the lion share of what we call an IT profession is the ability to solve them. The solutions for some most common problems you will find below, but it is only a matter of time when you encounter a new one that you will have to solve on your own. Search and experiment – are the most useful hints, and your most powerful friend is your favourite web search engine.

INTRODUCTION: ROADMAP
A usual choice for developers is to create a workplace on your own local computer. When your solution is completed and working you will then transmit files to a server. While at the development stage, you have all your files stored locally, available to be checked and tested in your browser right in the moment when you save them to the disk. Now, you have several ways you can go. Here are just some of them:  Download your development tools. There are many packages that contain all the necessary tools, including, most usually, Apache web server, MySQL database server and PHP scripting language. Together with Windows operating system they are commonly named WAMP (Windows, Apache, MySQL, PHP), or LAMP if you prefer Linux than Windows, or even MAMP if you are a Mac user. Their common feature is that they come in a form of open source installers, and require next to no time to install and setup. They are much more reliable now than they used to be, and in most cases the whole installation process is trouble-free. Especially if you are not yet an experienced developer, this approach may be recommended to you. There are many WAMP/LAMP/MAMP packages and they are easy to find through a search engine. My favourite project is a cross-platform package named XAMPP, where X stands for ‘Cross’, and the additional ‘P’ is for Perl. You can download XAMPP from http://www.apachefriends.org. Install and configure your PHP development environment all by yourself. It’s a more difficult path, but in the same time may be more awarding. Doing everything by yourself you will better understand your installation and you will be better prepared to cope with any possible problems. Unfortunately, I do not maintain any more this path – you may check an older version of this document at http://php.francik.name/old/php.pdf, but keep in mind it was written several years ago and the information may be not accurate for current versions of software. Use a different technology. PHP is still the most commonly used server-side scripting technology, but there are lots of alternative solutions. Personally, I don’t like PHP: it’s relatively easy, but it’s definitely outdated and tends to produce very messy code. What I really don’t like is that PHP does not support code-view separation, which is now a leading development approach and which makes larger projects much easier to maintain. Please see my other website, http://rails.francik.name, and say ‘hello’ to Ruby on Rails – one of the most dynamically developing web technologies ever! Look for ready to use solutions. There are plenty of open source projects around. For example, if you need to build an on-line shop, instead of creating your own one from scratch, it may make much more sense to look at projects like Shopify, Volusion, osCommerce, Magento or many, many others. They will save you a lot of programming time and allow to concentrate on what is really important in your project. If there are such fantastic tool around, it would be foolishness not to use them! But, note, this document does not cover this option.

If you installed MySQL manually. then create a table.01 Transitional//EN" "http://www.PHP FILE Ok. but may be done in several different ways depending on the tools you have. '8GB Memory Stick'.99'). What we have here is almost pure HTML. (4. you can find using phpMyAdmin tool easier. 'Soap'. image varchar(100) NOT NULL default ''.name. '2.dtd"> <html> <head> <title>Your Cart</title> <meta http-equiv="Content-Type" content="text/html.org/TR/html4/loose. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.49'). PRIMARY KEY (id) ). let’s start! This is an easy step. So. You can now exit the database command client. If what you have is preinstalled WAMP solution. . it’s HTML with embedded PHP snippets.00'.2\htdocs. It is typically C:\Program Files\Apache Software Foundation\Apache2. '1. We will use some simple SQL commands you should be well familiar with. (3. price decimal(6. 'Strawberry Jam'. Please open notepad (or any other text editor) and type the text in the frame below.99'). CREATE CART. CREATE TABLE goods ( id int(6) unsigned NOT NULL auto_increment. If you have a LAMP (Linux. MySQL and PHP all up and running on your machine). save the file in the htdocs directory of your Apache server. INSERT INSERT INSERT INSERT INTO INTO INTO INTO goods goods goods goods VALUES VALUES VALUES VALUES (1.w3. this is just a placeholder into which we’ll add some code later on. There are three simple steps to do: first you have to create a database named test (in some system there may already be a test database).99'). '22. The only piece of PHP code is between <?php and ?> markers – and this is what actually PHP code is. and finally – populate it with some sample data.PREPARE THE DATABASE So. item varchar(100) NOT NULL default ''. I assume you have by now a WAMP configuration (Windows. Just type them into your command line client or use import option in phpMyAdmin: USE test. you may use the MySQL Command Line Client. At this stage our PHP code section is empty. now we will start some coding. You can also download this file from http://php. charset=UTF-8" /> </head> <body> <h1>Your Cart</h1> <?php ?> </body> </html> Now. and name it cart.2) NOT NULL default '0. (2.php. Appache.francik. '4. …) – it’s fine as well. 'Toothpaste'. The htdocs is the directory created when you installed your Apache server.

The syntax is simple.</p>". 3.php?action=show This will tell our application that the action to do is show.php?action=add&id=2 Now. ?> All identifiers starting with $ sign (in the example above: $action and $id) are PHP variables. . 2. just put the following code into the <?php and ?> code snippet: <?php echo "Hello. we can use a special section added after the page URL. echo "<p>DEBUG: Action to do is $action. and also it is very easy to read the values the application gets from within your PHP code. MAKE THE INFORMATION PERSISTENT The information about the content of the cart needs to be persistent. like Microsoft Word or Open Office.To test your web application. and item id is $id. You’ve just done your first piece of PHP! DETERMINE WHAT THE APPLICATION SHOULD DO To tell what our application should do. go to http://localhost/cart. HELLO WORLD To do a classical programming exercise. $id = $_GET['id']. the action to do is add. still an id must be somewhere stored between consecutive visits so that the relevant records are addressed in the database. Keep your text editor and the browser open all time. When you change anything in your PHP script. It is difficult because the web http protocol is stateless – it has no knowledge about any previous operations. All the values are stored in a predefined array variable $_GET. You should see something similar to this: Your Cart Hints: 1. ?> Save the file and check the result in the browser (don’t forget to reload the page). and for this example notepad will be quite enough. to tell the application just to show the cart. In that case check carefully what is wrong or missing. For example. world!". Save the file and test the application with several different URL’s as shown above. We can also add items with the following URL: http://localhost/cart. It is however essential not to use text processors. as they add formatting information that is not accepted by PHP Processor. To edit your PHP file you can use any text editor. you can just save it (Ctrl S) and reload the page in the browser (F5) – you will see the results immediately! It will happen that your web application is not working. If the user returns to the cart several times before leaving the site. and additionally the id (of the item added) is 2. we will use: http://localhost/cart. The common errors are lacking quotation marks.php in your web browser. Check also spelling and keep in mind that PHP is case sensitive: echo is something completely different then Echo. semicolons or dollar signs. each time the content must be kept consistent. Fortunately PHP offers a very powerful and easy-to-use tool called session variables. which can be indexed by the name of the properties: <?php $action = $_GET['action']. Even if data is stored in a database.

echo "<p>DEBUG: Action to do is $action.dtd"> <html> <head> <title>Your Cart</title> <meta http-equiv="Content-Type" content="text/html. before even the !DOCTYPE.2.. and item id is $id. we have to split our <?php . we don’t even have to use the database to keep track of the items in the cart – everything we need is a session variable. there is one more important detail: most servers will require the session_start() to be called before the whole file starts.</p>". In a separate file (maybe index.w3. like this: <?php session_start(). that each time executing the script the value of the session variable is first stored into a local $cart variable.01 Transitional//EN" "http://www.php?action=add&id=3">Add item #3 to the cart</a></li> <li><a href="cart. } echo "<p>DEBUG: Cart is: $cart</p>". charset=UTF-8" /> </head> <body> <h1>Your Shop</h1> <ul> <li><a href="cart. We will use a variable named 'cart' which will be available as $_SESSIONS['cart']. Therefore.$id".. ?> section into two. the id of the item is added to the content of the cart.3’.1. Id’s are separated with commas.php?action=add&id=2">Add item #2 to the cart</a></li> <li><a href="cart. CREATE THE SHOP HOME PAGE With rudimentary but functional cart we can make a home page for the shop. Oops. ?> </body> </html> The new additions to the code are bolded. if the action to do is ‘add’.w3. $id = $_GET['id']. $action = $_GET['action']. To start using the sessions a single call must be done to function session_start(). ".org/TR/html4/loose.org/TR/html4/loose. charset=UTF-8" /> </head> <body> <h1>Your Cart</h1> <?php $cart = $_SESSION['cart'].php?action=add&id=4">Add item #4 to the cart</a></li> </ul> <p><a href="cart. and the new value is stored in a session variable. Notice.In fact. after adding a three items your cart state may be like this: ‘. ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.php?action=add&id=1">Add item #1 to the cart</a></li> <li><a href="cart. if ($action == 'add') { $cart = $cart . Therefore. Then.php) write the following HTML code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.php?action=show">Show your cart</a></p> </body> </html> . All the session variables are stored in an array called $_SESSION.dtd"> <html> <head> <title>Your Shop</title> <meta http-equiv="Content-Type" content="text/html. $_SESSION['cart'] = $cart.

// choose the test database . $cart). the foreach iteration will substitute consecutive items to the variable $i. // display if connection failed mysql_select_db("test".. $username. } $myitems = explode('. We also avoid displaying information in case the item id is an empty string.$id". // localhost is the URL of the server // the username in this example is root // put here your MySQL root password (maybe '' if none) // connect to the database server $con = mysql_connect($hostname. mysql_error()). foreach – a standard PHP loop that is capable to iterate through each item of an array. the only output are not very interesting DEBUG strings. $password = 'elvis'. CONNECT TO THE DATABASE Time came to connect to the database. $password) or die ('Could not connect: ' . // explode using comma as a separator if (count($myitems) <= 1) echo "<p>Your cart is empty. if ($action == 'add') { $cart = $cart . Provide the proper username and password! You can add new user accounts using Priviliges option in phpMyAdmin.. If it is not. .DISPLAY YOUR CART So far. $action = $_GET['action']. $_SESSION['cart'] = $cart. else foreach ($myitems as $i) if ($i != '') { echo "<p>Item id: $i</p>". ".'. Together.. $username = 'root'. } ?> After exploding the cart we first check if the cart is empty. they do exactly what we now need: <?php $cart = $_SESSION['cart']. Another great PHP tool we’ll use now are:   explode() – this function can transform a comma separated list into an array of items. It is essential if we want to display the name and price of items rather than just the id number.) or die (.. mysql_select_db chooses a database within the server.. $id = $_GET['id'].<p>". The sequence of operations necessary to open the connection is as follows: <?php $hostname = 'localhost'.. $con).   mysql_connect(.) creates a database server connection and displays a message if failed.

To achieve it..Client does not support authentication protocol is a common error at this stage. . It should be displayed in one line. Start the MySQL Command Line Client. FINAL POLISHINGS As the final polishing – some better formatting will be added (using HTML tables) and also the total price of the transaction will be calculated. Assure you terminate the SQL directive with a semicolon. The value returned by this function is a database table row. $row = mysql_fetch_array($result). So far. login and type: SET PASSWORD FOR 'root'@'localhost' = OLD_PASSWORD('elvis'). It is due to a change in the way the passwords are stored in the newer versions of MySQL and causes PHP passwords to be incompatible. it is hard-coded and not very interesting. foreach ($myitems as $i) if ($i != '') { $result = mysql_query("SELECT * FROM goods WHERE id = $i"). it is enough to reload the page to get the item added again. The final part of the PHP code will now look like this: . just three steps are needed:    Form a MySQL query – using mysql_query() function and standard SQL syntax.. DISPLAY YOUR CART IN A SMART WAY With a known id. That’s all. and a database connection.$price</p>".. The solution of the problem is easy – type the error message in Google and you’ll find it in the first result. We will also change the main (home) page of the store. we can now read the name and the price of each product from the database. with quantity and price indicated. $price = $row['price']. replacing 'elvis' with your real password. $item = $row['item']. } ?> Notice the use of the $i variable in creating the SQL query. We will now read from a database to make it more dynamic. echo "<p>$item: &pound. The row may be directly indexed with the names of table columns – like $row['item'] and $row['price']. When adding items. the script displays it in separate lines. There is no Delete function. Fetch the result – using mysql_fetch_array() function. Both – final – listings are shown in the following pages. SHORTCOMINGS AND POSSIBLE EXTENSIONS    If you buy the same item twice.

$cart). $item = $row['item']. ". mysql_error()). // localhost is the URL of the server // the username in this example is root // put here your MySQL root password (maybe '' if none) // connect to the database server $con = mysql_connect($hostname. // display if connection failed mysql_select_db("test". } ?> <p>[<a href="index. charset=UTF-8" /> <!--<link rel="stylesheet" type="text/css" href="style. foreach ($myitems as $i) if ($i != '') { $result = mysql_query("SELECT * FROM goods WHERE id = $i"). $password) or die ('Could not connect: ' .<p>". else { echo "<table>".css" />--> </head> <body> <h1>Your Cart</h1> <?php $hostname = 'localhost'.dtd"> <html> <head> <title>Your title here</title> <meta http-equiv="Content-Type" content="text/html. // explode using comma as a separator if (count($myitems) <= 1) echo "<p>Your cart is empty. $total = 0.php">Home Page</a>]</p> </body> </html> . // choose the test database $cart = $_SESSION['cart']. if ($action == 'add') { $cart = $cart .w3.'. $row = mysql_fetch_array($result). echo "<tr><td>$item</td><td>&pound. } echo "<tr><td><strong>Total</strong></td><td><strong>&pound. $total += $price. $password = 'elvis'. $action = $_GET['action']. $username = 'root'. $price = $row['price'].01 Transitional//EN" "http://www. echo "</tr></table>". $_SESSION['cart'] = $cart. ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. $id = $_GET['id'].$total</strong></td>".$id".org/TR/html4/loose.$price</td></tr>".php: <?php session_start().cart. $con). } $myitems = explode('. $username.

}.dtd"> <?php $hostname = 'localhost'.css" />--> </head> <body> <h1>Your Shop</h1> <table> <?php $result = mysql_query("SELECT * FROM goods"). ?> </table> <p><a href="cart. $password) or die ('Could not connect: ' . $username = 'root'.index. $price = $row['price']. mysql_error()).01 Transitional//EN" "http://www. echo "<td>&pound. $item = $row['item']. charset=UTF-8" /> <!--<link rel="stylesheet" type="text/css" href="style. // choose the test database ?> <html> <head> <title>Your Shop</title> <meta http-equiv="Content-Type" content="text/html.php?action=show">Show your cart</a></p> </body> </html> . echo "<tr>". echo "<td>$item</td>".php: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. echo "<td><a href=\"cart. // localhost is the URL of the server // the username in this example is root // put here your MySQL root password (maybe '' if none) // connect to the database server $con = mysql_connect($hostname.w3. echo "</tr>". $username. $con). mysql_free_result($result). while ($row = mysql_fetch_array($result)) { $id = $row['id']. $password = 'elvis'.org/TR/html4/loose.$price</td>".php?action=add&id=$id\">add to cart</a></td>". // display if connection failed mysql_select_db("test".

and the address is http://ftemysql. just copy the error message and paste it to the Google search box. Identify your source files: index. change the username from root to your k-number based username c. read both his posts. 3. but the password system is different from the university main one! At the first login. You have to check if the server supports php and offers mysql database access.php. You also have the unique access to the university mysql server! You can only login from within the university.php and cart. You will probably not be very much satisfied with the results. 5. password etc. Alternatively. Do some research. Edit cart.ac.kingston. user accounts. 2. These steps will guide you through the process: 1. If you are still confused. and you’ll get a ‘new’ one to your mailbox. change the database name from test to your k-number. You can also use or find a hosting company to get (buy) your own server space. check http://www.phpbuilder.php and make the following amendments: a.com/board/showthread. avoiding installing everything locally – however you will need to ftp your files each time you change anything – not a very good idea. change the password from elvis to your actual password at the ftemysql server d. The steps required to port your application will be similar to those described above. Paste your source code into the files. If you don’t know the solution (which is likely). change the hostname from localhost to ftemysql b.php?t=10309672 for the solution provided by Subwayman. Notice that due to a small bug you will always have to login twice! To deploy your application. You are provided with your own private web space at http://studentnet. Use your k-number as the username.name site to populate them with the source code. you actually will need to port it: all the host addresses. See the results. 6. 4. Use your favourite ftp client to send the files to the studentnet. just pretend you’ve forgot your password. .uk/~kXXXXXX.APPENDIX: DEPLOYMENT ON KINGSTON UNIVERSITY SERVER Kingston University provides a special studentnet server which you can use to deploy your application. You can use studentnet to develop your application.francik. you can create empty files with these names and use http:// php. This is in the mysql_select_db function call. You also have regular ftp access there (your usual k-number username and password will work). where kXXXXXX stands for your university k-number. must be fixed to comply with the new environment.

Sign up to vote on this title
UsefulNot useful