Web Design → PHP challenges This page is part of the Web Design project.

Challenge 1: Idiot Box Survey [ edit | edit source ]

A very old TV

Scenario: You are working as IT Support for a small high school in your area. The Parents and Community committee has commissioned a small project to help kids in the school work out exactly how much time they're spending in front of the TV, Computer or Video Game Consoles, as well as collect data on how free time is spent.

Creating the form [ edit | edit source ]

You've been asked to whip up a prototype form to collect the following info (remember your target audience when labeling your fields!):

First and last name

Number of Years in Business

Year at School (e.g. 7-12)

Number of siblings

At what time do they go to bed, and at what time do they wake up.

Approximate time spent on homework per day

time spent watching TV/DVD etc. per day

Time spent using computer or games console per day

time spent with family per day

time spent with friends per day

You do not necessarily need to make your form pretty or worry about Javascript input validation for the prototype, but it certainly needs to be easy to use. For example:

<!DOCTYPE html> <html> <head> <title>colls data</title> </head> <body> <form action="process.php" method="POST"> FIRST NAME: <input type="text" name="name1"> LAST NAME: <input type="text" name="name2"> AGE: <input type="text" name="age"> <br> <br> GRADE: <input type="text" name="grade"> <br> <br> How many siblings do you have?: <input type="text" name="siblings"> <br> <br> At what time do you go to bed?: <input type="time" name="sleeps"> <br> < br> At what time do you wakeup?: <input type="time" name="wakes"> <br> <br> what is the approximate time you spent on your homework per day?: <input type="time" name="homework"> <br> <br> what is the approximate time you spent watching TV/DVD per day?: <input type="time" name="TV/DVD"> <br> <br> what is the approximate time you spent using computer or games console per day?: <input type="time" name="comp/games"> <br> <br> what is the approximate time you spent with family per day?: <input type="time" name="familytime"> <br> <br> what is the approximate time you spent with friends per day?: <input type="time" name="friendstime"> <br> <p><b>hint click the clock icon to select time</b></p> <br> <br> <input type="submit" name=""> </form> </body> </html>

Processing your form [ edit | edit source ]

Your prototype will also require a php script (or server-side language of your choice) to process the info. The P&C committee have asked for the following:

A message saying "Great! Thanks [firstname] for responding to our survey".

A display of the students details formatted suitably (just name, birth-year, current school year and number of siblings)

An email should be sent to a set email address with a subject of, for example, "David Terry's Survey results." and a message that includes the data entered (no need to worry about formatting or headers in the email).

Challenge 2: Idiot Box Statistics [ edit | edit source ]

You receive an email from the P&C Committee asking that once you have this working, your challenges are to modify your response so that it also says: "Based on the information you've entered, you will spend:"

x hours watching TV or movies per year.

hours watching TV or movies per year. y hours doing homework per year.

hours doing homework per year. z hours per year in front of a TV or computer screen per year

hours per year in front of a TV or computer screen per year a hours per year with friends and family per year

Note, this information does not need to be included in the email. With this you will be ready to demonstrate your prototype!

Extra challenges [ edit | edit source ]

Not for the faint-hearted!

Use the students' current year at school to work out how many years they have left at school, and from this, how many hours they will spend doing homework or watching a screen until they finish school.

Work out the percentage of awake time spent in front of a screen.

Challenge 3: Combining Your Form and Response [ edit | edit source ]

After working through Part 3 of Zend's PHP for beginners series, you've worked out that it's a bit neater to put all your code into the one file (rather than having separate files for your form and form processing).

Modify your prototype from Challenge 1 to use just one php file that either displays your survey form or processes the results, depending on whether the form has been submitted (based on the tutorial).

Challenge 3.5: Looping the Loop [ edit | edit source ]

Part 3 of Zend's PHP for beginners also gives you an overview of a few different ways that you can repeat stuff in your PHP code. The following challenges are designed to help you re-enforce in your mind how while loops and for loops can be used.

Take a look at the following piece of code and work out what it does as you read through it, then copy-n-paste it into a PHP file to test it out.

$x = 0 ; while ( $x < 10 ) { print ( "<p> $x </p>" ); $x ++ ; }

Your challenges:

Modify the loop so that it displays the numbers from 1 to 100

Modify the loop so that it displays the even numbers between 1 and 100

Modify the loop so that it displays the numbers from 100 to 1 (i.e. in reverse order)

The above while loop can also be written in other ways (such as a for-loop), but for the moment, it's best that you learn how to use one method well. For those who are interested and feel very confident, you might want to look through the following code (otherwise just skip over it!)

for ( $x = 1 ; $x < 10 ; $x = $x + 1 ) { print ( "<p> $x </p>" ); }

PHP Manual - for loops does a great job explaining why you have three different things in the first line: for (part1; part2; part3). If you are keen to try out the for loop, you can do all of the above challenges, but using a for-loop instead of a while loop. Now, use the above to:

Copy-n-paste and modify the above piece of code so that it prints the numbers as a single unordered list. i.e. the HTML output should look like:

< ul > < li > 1 </ li > < li > 2 </ li > ... < li > 100 </ li > </ ul >

Last but not least,

Copy-n-paste and modify your code to create a simple form that allows the user to select the day of the month that they were born. i.e. the HTML output should look something like:

< form > < p > Name: < input type = "text" name = "fullname" /></ p > < p > Day of month you were born: < select name = "dayofmonth" > < option > 1 </ option > < option > 2 </ option > ... < option > 31 </ option > </ select > </ form >

Challenge 4: Input Validation with PHP [ edit | edit source ]

Below is an example IF statement that will check if a user has entered any information into the 'first_name' field. Your challenge is after the example!





first_name would be assigned to a form element, like: < input type = "text" name = "first_name" /> name attribute gets attached to the POST DATA. In the HTML,would be assigned to a form element, like:Whatever is in theattribute gets attached to the POST DATA.



Now, for the IF statement in your PHP code:

if ( $_POST [ 'first_name' ] != "" ) { print ( "Yes, the input box: 'first_name' was filled in!" ); print ( "And the contents of this input box was: $_POST['first_name'] " ); } else { print ( "The input box 'first_name' had nothing in it." ); }

The first line of code checks for one thing, shown below:

It checks if first_name is NOT equal to an empty string.

$_POST [ 'first_name' ] != ""

If this is TRUE then the following will be printed:

Yes, the input box: 'first_name' was filled in! And the contents of this input box was: Frank

But, if what the IF-statement checks is not true then the following will be printed:

The input box 'first_name' had nothing in it.

Your challenge is to use the above example to validate your Idiot box survey form! Remember, always break the problem down into small chunks... start by validating just one field, then when that works, add the next etc. (If you're already using JavaScript form validation for this exercise, you'll need to switch it off to test your PHP input validation!

Challenge 5: Putting Stuff into a DB [ edit | edit source ]

The P&C committee is happy with your prototype and have given you the go-ahead to develop the database functionality.

This challenge will require you to:

create the database table using PhpMyAdmin (or similar),

Using PhpMyAdmin, add some data to your database and note the SQL query that was used to add the data (copy the complete query).

Update your form processing code so that after displaying the results your code

Connects to your database server Selects your database Runs the query that PhpMyAdmin generated for you Closes the connection to your database server

Here's some template code to get you started:

<?php // // Step 1: Connecting to the database server // print ( "<h2>Step 1: Connecting to the database server</h2>

" ); print ( "<p>First we need to connect to the database server:</p>

" ); // // Try connecting to the database server... you'll need to replace // your database server, username and password! // (Note that in real world production systems it is considered bad // practice to 'hard-code' authentication credentials within your // programs. Instead, you should store them outside of the code and // load them when necessary.) // $result = mysql_connect ( "your_db_server" , "username" , "passwd" ); // // We'll check to make sure that the connect worked using an if-statement // Once the page is successfully displaying the desired results, we can // simply comment out all these 'if' statements that check for errors. // if ( ! $result ) { print ( "<h2>Failed to connect to database!</h2>" ); } else { print ( "<p>Connection established</p>" ); } // // Step 2: Selecting the database // print ( "<h2>Step 2: Selecting the database</h2>

" ); $result = mysql_select_db ( "your_db_name" ); if ( ! $result ) { print ( "<h2>Failed to select database!</h2>" ); } else { print ( "<p>Database selected successfully</p>" ); } // // Step 3: Run an SQL query! // First create the query in a variable of our own called $sql, then // run the query using the special mysql function. You might want to // insert info into your DB using phpMyAdmin to find out exactly // how your INSERT statement will look! // print ( "<h2>Step 3: Run a SQL query!</h2>" ); $sql = "INSERT INTO blah ... rest of your INSERT statement goes here;" ; $result = mysql_query ( $sql ); // As usual, check to make sure that it worked: if ( ! $result ) { print ( "<h2>Failed to run the query! Error is:" . mysql_error () . "</h2>" ); } else { print ( "<p>Query ran successfully!</p>" ); } // // Step 4: Process the results // When we're inserting information into a database, we don't actually // have any results to process... this'll come later when we're getting // data out of a database. So, we can skip step 4 for now! // // // Step 5: Close the connection with the database server // Although we don't _really_ need to do this (it'll be done for us) // it's good for us to know that it happens. // print ( "<h2>Step 5: Close the connection to the database server</h2>

" ); mysql_close (); ?>

Once the last step has been tested and works (you'll need to check whether the test information has actually made its way into your database), modify your query so that the actual information entered into the form is inserted into your database and test it again.

Challenge 6: Getting Stuff out of a DB [ edit | edit source ]

After reviewing your form for entering new data for the survey, the P&C committee ask you to create a page that displays all the collected data.

You warn them that they will need to implement some security around this function before going live with the survey application (so that only certain people can view the information), but you agree to get a prototype going to show them how it will work (i.e., you don't need to worry about the security issue for the moment!).

Step-by-step:

Create a special page of your site that displays the data from your table. Here's some template code to look through, modify and try out:

<!DOCTYPE html> <html> <head> <title>Getting info from a database</title> </head> <body> <h1>Getting info from a database into PHP</h1> <?php // // Step 1: Connecting to the database server // print ( "<h2>Step 1: Connecting to the database server</h2>

" ); print ( "<p>First we need to connect to the database server:</p>

" ); // // Try connecting to the database server... you'll need to replace // your database server, username and password! // $result = mysql_connect ( "your_db_server" , "username" , "passwd" ); // // We'll check to make sure that the connect worked using an if-statement // Once the page is successfully displaying the desired results, we can // simply comment out all these 'if' statements that check for errors. // if ( ! $result ) { print ( "<h2>Failed to connect to database!</h2>" ); } else { print ( "<p>Connection established</p>" ); } // // Step 2: Selecting the database // print ( "<h2>Step 2: Selecting the database</h2>

" ); $result = mysql_select_db ( "your_db_name" ); if ( ! $result ) { print ( "<h2>Failed to select database!</h2>" ); } else { print ( "<p>Database selected successfully</p>" ); } // // Step 3: Run an SQL query! // First create the query in a variable of our own called $sql, then // run the query using the special mysql function // print ( "<h2>Step 3: Run an SQL query!</h2>" ); $sql = "SELECT * from upload;" ; $result = mysql_query ( $sql ); // As usual, check to make sure that it worked: if ( ! $result ) { print ( "<h2>Failed to run the query! Error is:" . mysql_error () . "</h2>" ); } else { print ( "<p>Query ran successfully!</p>" ); } // // Step 4: Process the results // This part is the tricky part... lots of new learning... have a coffee // before getting through this. // print ( "<h2>Step 4: Process the results</h2>

" ); // // Get the first row from the result of our query. Note, mysql_fetch_array() // returns a value of false if there's no more results left. // $row_array = mysql_fetch_array ( $result ); while ( $row_array != false ) { // print out whatever we want from this row print ( "<p>Filename: " . $row_array [ "filename" ] . ".</p>

" ); // before trying to get the next row! $row_array = mysql_fetch_array ( $result ); } print ( "<h2>Step 5: Close the connection to the database server</h2>

" ); mysql_close (); ?> </body> </html>

After getting the above template code to work with your database (and more importantly, verifying that you understand how it's working, especially the while loop):

Modify the code above so that, instead of each row of your table being displayed as a paragraph, each row is outputted as a row of an HTML table.

Challenge 7: Displaying Details for One Record [ edit | edit source ]

The following week you meet up with the committee again to demonstrate your work. The committee is impressed to see that you've formatted the survey information in a nice table, but have a few concerns. The biggest concern of the committee is that it is a lot of information to display on the screen at once.

They would like to modify the application so that when the survey results from the database are displayed, only the following information is included in 3 columns:

Name: first name and last name,

Total hours spent in front of a screen per week,

Total hours spent with friends and family per week.

Furthermore, when these results are displayed, the committee would like to be able to click on the name of a student to view the details for that student.

On a piece of paper, see if you can break down your task into a number of steps to tackle (before going on)!

Step-by-step:

Modify your results from Challenge 6 so that each row displays the name, Screen hours per week and Social hours per week and test.

Add the following link around each student name: <a href="details.php?id=4" title="View student details" ></a> Note that this linking URL contains some extra information so that the file details.php will know which student we want to view. Make sure the links appear.

Create a new file called details.php with the normal HTML structure. Initially, just add the following PHP code inside the body (Note, it includes an intentional error):

$student_id = $_POST [ "id" ]; // For security reasons, ensure that our input consists only of numbers $student_id = preg_replace ( '/[^0-9]/' , '' , $student_id ); print ( "<h2>You have requested to view the details of the student with the id=" . $student_id . "</h2>" );

Test this code by entering the URL "yourdomain.com/path_to_your_file/details.php?id=4" into your browser and see if you can get it working.

Hint 1: We've incorrectly used the $_POST array, even though we haven't actually posted any information from a form using the method="post". Hint 2: Instead we want to GET the information that was sent through the URL.

Once you think it's working, modify the url in your browser to "details.php?id=2" to see if it really is working! Next,

Check out the W3Schools explanation of the $_GET array in PHP.

Use PHPMyAdmin to see if you can find out the SQL query that will return one specific row of your database table (i.e., you want to select all the fields from your table WHERE the id is equal to 4.) Test that it works in PHPMyAdmin using other values for the ID.

Add the code to your details.php to:

Connect to the database server, Select your database, Run your SQL query, Display the result of your query (Note: you won't need a while loop this time, as there should only ever be one result! You can use an if statement instead to make sure that your query did return a result)

Test that this works, first by entering the URL in your browser "details.php?id=4", then change the id to display different records.

Now the only remaining problem is that every student listed on our summary page links to the one student details page (the student with the id=4). The last element of this challenge is:

Modify the link around each student name so that each link contains the corresponding id for that student.

Challenge 8: Deleting Stuff from a Database [ edit | edit source ]

If you've come this far, then your PHP/MySQL skills have come a long way! This challenge provides hints, but doesn't give you the details. You'll need to work hard and use your resources well!

Hints:

Update your page that displays all the records, to include an extra column for each record that simply has the text "delete", or if you prefer icons, a little trash-can icon.

Add the following link around your trashcan icon: <a href="?deleteid=4" title="Delete this record"></a>

Modify your page so that, when your delete link is clicked, your page displays the text "The record with the id of 4 would have been deleted" (you'll need to put this inside an if-statement so that it only appears when the user has clicked on one of your delete links).

Use PHPMyAdmin to find the SQL syntax required to delete an item from your database.

Update your if-statement so that your code runs the SQL query to delete the record.

Once you have your delete functionality working, it would be a great time to add a very simple menu to your survey application so that you can navigate between the form and the summary page (where you can delete records or view the details of records).

Lastly:

Add a link to the details page (where you view the details of one particular record, from Challenge 7) to delete the current record!

Challenge 9: Putting It All Together [ edit | edit source ]

After completing your survey application for the local Parents and Community committee, your application was used by hundreds of schools in your state! Everyone loved it! And lots of people saw your web application skills in action!

Now you've been approached by the department to develop a prototype for a school enrolment application! At the moment the application will just be for one school and will need to:

Allow new students to be added, assigning them to a certain year. Required info: first and last name, D.O.B., Enrollment Date Current School year (e.g. 7-12), home phone, mobile, email, 1st Contact name (usually parent), 1st Contact phone, 2nd Contact name, 2nd Contact phone.

View a summary of all the students currently enrolled at the school, sorted by year and then name. The summary should include the students name, school year and email.

View the details of a particular student.

Delete a student (both from the summary view as well as from the individual view).

After discussing the prototype with your client contact, you also thought of a few improvements that you might add if you have time:

Making the email displayed on the summary view a link that can be clicked on. For example:

< a href = "mailto:tom.jones@mymail.com" > Tom Jones </ a >

Including a link on the summary view to edit a student record. This will bring a form up that is identical to the new student form, but with all the fields pre-populated from the record in the database.

The ability to upload a photo for a student (to help teachers and administrators put names to faces!)

A short report that shows from the database how many students are currently enrolled in each year.

This is your chance to get your business off the ground! A contract with the Education department will help pay the bills!

Once you finish your prototype, it will be worth discussing with others how your database design could be improved too.