Task 03


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Task 03

  1. 1. Task Sheet 03 EdiPHP Students PHP Meetup November 11, 2009 This is the third task sheet of EdiPHP. If you’re stuck on the tasks, or find a mistake in them, or simply want to have a chat, feel free to contact us via our Facebook group or Twitter account. 1 Introduction Imagine that your friend earns his living creating personalised lolcat pictures with captions and then selling them. He usually gets an order from the customer in the following manner: ”I would like a ceiling cat saying something cute, you know, like this, but more like, you know..”. As this is not very informative, he, together with the customer processes the order so it now contains the following information: • Cat category; • Cat mood; • Abstract description of caption. As this is already a clearer solution, it may sometimes be hard to understand moods like ”the same as my wife’s”, so he categorises them even further. Currently he has four categories of cats: Ceiling cat, Basement cat, Monorail cat, Long cat. He also have five categories for moods: cute, happy, sad, ignorant, a killer. He does not categorise the description of a caption, as it is too hard to do that. He also changes his categories from time to time, removing old ones that nobody orders any more, adding new, etc. Everything went fine for your friend until this year, when the order count increased sharply. The friend found himself spending more time ”processing” the orders, than actually making the lolcat pictures. ”Can’t I make the processing automatic?”, he thought once, and asked you for help with that. 1
  2. 2. 2 The Task We will create an automatic lolcat picture ordering system. Our system will have: • a form where user could choose the categories of lolcats and moods, and submit it; • a page where our friend could see all orders. (not necessary) Easy enough? Let’s begin. 3 Task 0 - Get phpMyAdmin First of all, we should get a tool to manage our database. We’ll use phpMyAdmin. XAMPP users should already have it out of the box at http://localhost/phpMyAdmin/, others should ask google on how to setup it. :) 4 Task 1 - Create a form I won’t go in this part in detail, as you should already know how to create a form from the previous task. Your form should have the following items in it: • an <select> field that would contain the lolcat type categories; • an another <select> to contain the moods; • an <input type="text"> that will contain our description; • a submit button; The fields should be easy to manage and populate with data. You can find information about <select> fields at w3schools. It would be convenient to create <option> elements in a select from an array of strings, though it is your own choice, how to implement those (you can also go for add one at time). The values of <option> elements should be integers from 0 to count($elements), corresponding to item numbers in array. The contents of option should be string values like ”Ceiling Cat”, ”Volvo” (see below) etc. Your form must not allow to leave a description field empty. And check explicitly whether selected option of the <select> field actually is valid. For instance, if you have the following: <select name="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> 2
  3. 3. (just copied this from w3schools and added a name field) Your form must treat $_POST[’cars’] = ’bmw’ as invalid data, as bmw is not in the list of options. 4.1 Order object Valid form should generate a message, stating that it is valid. Valid form should also create an Order object, where class Order has these variables: • categoryId; • moodId; • description. together with their setters and you should be able to create them from post data easily. 5 Task 2 - Prepare The Database Turn on your phpMyAdmin and create a new database there. It should be obvious enough how to do that. Call it whatever you like to call it, but I will refer to it as orders db. Here’s how orders db would look like: orders id moods mood_id id mood_id id category_id name description category_id id categories id name As you can see, we will have three tables: moods, categories, orders which are related together by their id’s. Let’s create them one at a time. To create a new table find a method of similar name in phpMyAdmin. Input your table name and how many fields will it have. Then input your fields and select their types. All fields labelled id, mood id, category id will by of type INT(11). All other fields will be VARCHAR(X) where X is the maximum length (character count) of the field (choose any you like, i.e. 100). Fields id in all three tables will be PRIMARY KEYS and should have auto increment property. phpMyAdmin is easy enough to use, so you should be able to set correct types and create the tables. Also insert some values of the fields into the database (this is done separately from creating it). Add moods and categories from the first page, as well as a few random orders. 3
  4. 4. 6 Task 3 - Interact with database Cool. You’ve created the database. Now let’s try to use it! All you need to know about interacting with database with PHP can be found here: mysql connect(), mysql select db(), mysql query(), mysql fetch object() It would also be useful to know that default username in XAMPP and, mostly, everywhere is ”root” and default password is ”” (empty string). 6.1 Create a class that interacts with database Let’s create a class that with directly deal with the database. The class should be able to connect to the database (using mysql_connect() and mysql_select_db()) while constructing it. The class should also have methods query($query) that executes a query and fetchAll($query) that returns all results of the query executed in any form you choose. The PHP documentation should provide enough information on how to do these methods. 6.2 Implement methods for fetching all moods and categories from the table Now we’ll create a method that fetches all categories from the database, lets call it getCategories(). It should return an array id => name, so it is easy to populate select field. This can be done by fetchAll("select * from ‘categories‘") and refactoring the result into the array above form. The query I wrote simply means ”select and return everything from the table cat- egories”. You can find more info about queries in MySQL documentation. Do similar thing with the moods table and getMoods() 6.3 Implement a method to insert orders into database Call the method addOrder(Order $order). You should use your query() method this time, as well as INSERT query (w3schools will help you). Don’t forget to escape your values (even integers) before inserting them to the database, you don’t want to be SQL injected, do you? 6.4 Wire it all together Wire your form together with the database: generate <option>s for <select>s from getCategories() and getMoods() methods, and submit the order to database if the form is valid. You can view the submitted orders by preview function in phpMyAdmin. Now let’s only teach our friend how to use phpMyAdmin, though it would be easier to create another page with fetchAll("SELECT * from ‘or and pretty printing, so he could view the orders, and we’re done. 4
  5. 5. 7 Conclusion This is a very basic example of interacting with databases from PHP. There are way better techniques of doing what we have done today, however it would take too long to cover them here. You will learn them when you will be learning PHP frameworks. If you don’t find this task hard enough, here are some optional exercises for you: • Add functionality so your friend could mark orders as ”completed” or ”not completed yet” • Add timestamps, contact details to orders, notify clients on completion. • Create a log in page. • Assign a (different) price to categories of lolcats and write an order price calculator. • Implement a page where your friend could edit available categories and moods - add new, amend, delete, etc. And that is all. Good luck from EdiPHP. 5