SlideShare a Scribd company logo
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     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
(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
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
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

More Related Content

Viewers also liked

ACTIVIDAD 2
ACTIVIDAD 2ACTIVIDAD 2
ACTIVIDAD 2
Jose O Cuellar
 
Lucky
LuckyLucky
Lucky
jmcgonigal
 
01 - First Meetup
01 - First Meetup01 - First Meetup
01 - First Meetup
EdiPHP
 
Task 2
Task 2Task 2
Task 2
EdiPHP
 
Fit4 Business
Fit4 BusinessFit4 Business
Fit4 Business
MaartenGKN
 
Historical Development Patterns
Historical Development PatternsHistorical Development Patterns
Historical Development Patterns
Eugene Water & Electric Board
 
Managing Religious Tourism Abstracts
Managing Religious Tourism   AbstractsManaging Religious Tourism   Abstracts
Managing Religious Tourism Abstracts
eon
 
Trabajo Excel Mate
Trabajo Excel MateTrabajo Excel Mate
Trabajo Excel Mate
valef94
 
Ppt Ingles
Ppt InglesPpt Ingles
Ppt Inglesvalef94
 
Collaborative Learning Solutions
Collaborative Learning SolutionsCollaborative Learning Solutions
Collaborative Learning SolutionsMaartenGKN
 

Viewers also liked (11)

ACTIVIDAD 2
ACTIVIDAD 2ACTIVIDAD 2
ACTIVIDAD 2
 
Lucky
LuckyLucky
Lucky
 
01 - First Meetup
01 - First Meetup01 - First Meetup
01 - First Meetup
 
Tornadoes keynote1
Tornadoes keynote1Tornadoes keynote1
Tornadoes keynote1
 
Task 2
Task 2Task 2
Task 2
 
Fit4 Business
Fit4 BusinessFit4 Business
Fit4 Business
 
Historical Development Patterns
Historical Development PatternsHistorical Development Patterns
Historical Development Patterns
 
Managing Religious Tourism Abstracts
Managing Religious Tourism   AbstractsManaging Religious Tourism   Abstracts
Managing Religious Tourism Abstracts
 
Trabajo Excel Mate
Trabajo Excel MateTrabajo Excel Mate
Trabajo Excel Mate
 
Ppt Ingles
Ppt InglesPpt Ingles
Ppt Ingles
 
Collaborative Learning Solutions
Collaborative Learning SolutionsCollaborative Learning Solutions
Collaborative Learning Solutions
 

Similar to Task 03

WordPress Theme Design - Rich Media Institute Workshop
WordPress Theme Design - Rich Media Institute WorkshopWordPress Theme Design - Rich Media Institute Workshop
WordPress Theme Design - Rich Media Institute Workshop
Brendan Sera-Shriar
 
forms
formsforms
forms
formsforms
Default theme implementations: a guide for module developers that want sweet ...
Default theme implementations: a guide for module developers that want sweet ...Default theme implementations: a guide for module developers that want sweet ...
Default theme implementations: a guide for module developers that want sweet ...
John Albin Wilkins
 
Wordcamp St. Louis - Clean Coding
Wordcamp St. Louis - Clean CodingWordcamp St. Louis - Clean Coding
Wordcamp St. Louis - Clean Coding
inspector_fegter
 
Zend Framework And Doctrine
Zend Framework And DoctrineZend Framework And Doctrine
Zend Framework And Doctrine
isaaczfoster
 
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
LinnAlexandra
 
srt311 Project2
srt311 Project2srt311 Project2
srt311 Project2
trayyoo
 
Introduction To Drupal
Introduction To DrupalIntroduction To Drupal
Introduction To Drupal
Lauren Roth
 
How to Develop Your First Ever Joomla Template?
How to Develop Your First Ever Joomla Template?How to Develop Your First Ever Joomla Template?
How to Develop Your First Ever Joomla Template?
damienwoods
 
Access tips access and sql part 4 building select queries on-the-fly
Access tips  access and sql part 4  building select queries on-the-flyAccess tips  access and sql part 4  building select queries on-the-fly
Access tips access and sql part 4 building select queries on-the-fly
quest2900
 
Using pandas library for data analysis in python
Using pandas library for data analysis in pythonUsing pandas library for data analysis in python
Using pandas library for data analysis in python
Bruce Jenks
 
lab56_db
lab56_dblab56_db
lab56_db
tutorialsruby
 
lab56_db
lab56_dblab56_db
lab56_db
tutorialsruby
 
Deck 6-456 (1)
Deck 6-456 (1)Deck 6-456 (1)
Deck 6-456 (1)
Justin Ezor
 
Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18
Thinkful
 
PrestaShop Kathmandu Ecommerce Meetup #2
PrestaShop Kathmandu Ecommerce Meetup #2PrestaShop Kathmandu Ecommerce Meetup #2
PrestaShop Kathmandu Ecommerce Meetup #2
Hem Pokhrel
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
Vibrant Technologies & Computers
 
Writing your own WordPress themes and plugins
Writing your own WordPress themes and pluginsWriting your own WordPress themes and plugins
Writing your own WordPress themes and plugins
Stephanie Wells
 
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Christian Lilley
 

Similar to Task 03 (20)

WordPress Theme Design - Rich Media Institute Workshop
WordPress Theme Design - Rich Media Institute WorkshopWordPress Theme Design - Rich Media Institute Workshop
WordPress Theme Design - Rich Media Institute Workshop
 
forms
formsforms
forms
 
forms
formsforms
forms
 
Default theme implementations: a guide for module developers that want sweet ...
Default theme implementations: a guide for module developers that want sweet ...Default theme implementations: a guide for module developers that want sweet ...
Default theme implementations: a guide for module developers that want sweet ...
 
Wordcamp St. Louis - Clean Coding
Wordcamp St. Louis - Clean CodingWordcamp St. Louis - Clean Coding
Wordcamp St. Louis - Clean Coding
 
Zend Framework And Doctrine
Zend Framework And DoctrineZend Framework And Doctrine
Zend Framework And Doctrine
 
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
 
srt311 Project2
srt311 Project2srt311 Project2
srt311 Project2
 
Introduction To Drupal
Introduction To DrupalIntroduction To Drupal
Introduction To Drupal
 
How to Develop Your First Ever Joomla Template?
How to Develop Your First Ever Joomla Template?How to Develop Your First Ever Joomla Template?
How to Develop Your First Ever Joomla Template?
 
Access tips access and sql part 4 building select queries on-the-fly
Access tips  access and sql part 4  building select queries on-the-flyAccess tips  access and sql part 4  building select queries on-the-fly
Access tips access and sql part 4 building select queries on-the-fly
 
Using pandas library for data analysis in python
Using pandas library for data analysis in pythonUsing pandas library for data analysis in python
Using pandas library for data analysis in python
 
lab56_db
lab56_dblab56_db
lab56_db
 
lab56_db
lab56_dblab56_db
lab56_db
 
Deck 6-456 (1)
Deck 6-456 (1)Deck 6-456 (1)
Deck 6-456 (1)
 
Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18
 
PrestaShop Kathmandu Ecommerce Meetup #2
PrestaShop Kathmandu Ecommerce Meetup #2PrestaShop Kathmandu Ecommerce Meetup #2
PrestaShop Kathmandu Ecommerce Meetup #2
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
Writing your own WordPress themes and plugins
Writing your own WordPress themes and pluginsWriting your own WordPress themes and plugins
Writing your own WordPress themes and plugins
 
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 

Task 03

  • 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 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. (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. 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. 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