Web Design/PHP challenges

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

PHP Challenge 1: Idiot Box Survey

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

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

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.

Processing your form

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:

PHP Challenge 2: Idiot box statistics

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:"

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

Extra challenges

Not for the faint-hearted!

PHP Challenge 3: Combining your form and response

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).

PHP Challenge 3.5: Looping the loop

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:

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:

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

Last but not least,

  <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>

PHP Challenge 4: Input validation with PHP

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!


(note: in the HTML, 'first_name' would be assigned to a form element, like:

<input type="text" name="first_name" />

Whatever is in the "name" attribute 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!

PHP Challenge 5: Putting stuff into a DB

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:

  1. Connects to your database server
  2. Selects your database
  3. Runs the query that PhpMyAdmin generated for you
  4. 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>\n");
print ("<p>First we need to connect to the database server:</p>\n");

//
// 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>\n");
$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 an 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>\n");
mysql_close();

?>

PHP Challenge 6: Getting stuff out of a DB

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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<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>\n");
print ("<p>First we need to connect to the database server:</p>\n");

//
// 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>\n");
$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>\n");


//
// 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>\n");
  
  // 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>\n");
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):

PHP Challenge 7: Displaying details for one record

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:

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:

  $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,

  1. Connect to the database server,
  2. Select your database,
  3. Run your SQL query,
  4. 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:

PHP Challenge 8: Deleting stuff from a database

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... so you'll need to work hard and use your resources well!

Hints:

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:

PHP Challenge 9: Putting it all together

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:

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

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

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.

This article is issued from Wikiversity - version of the Sunday, March 06, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.