Inspect code with Chrome

Anyone who codes makes mistakes, so it's no surprise that browsers  include robust tools that help coders find their mistakes. This lesson focuses on the Chrome console, but don't forget that Firefox and Safari have similar tools.

  1. To begin, visit and click the next button. Nothing happens because candidates.html is connected to candidates.js which has an error in its code.
  2. Right-click on candidates.html, and then click Inspect on the drop-down menu that appears.
  3. A list of elements should appear as shown below. To find the error, click on console.

  4. At this point you should a message that indicates that the problem is on line 24 of candidates.js.  Click on candidates.js:24 and candidates.js will open. You probably can spot the error (a missing > ) on line 24.

Of course if you were working on candidates.js in Brackets, you could not just find, but immediately correct your mistake.

The main point

Code inspectors are great tools and you owe it to yourself to use them. There is however, one caveat, if you are using Brackets. Live preview generates a lot of additional code that can make the inspection process more difficult. You usually are better off to click on the html file and open it directly in Chrome.

Introduction to Arrays

Arrays are one of the most commonly used methods for storing and accessing data. In this lesson we will learn how to extract data from arrays and use it to populate a web page.

  1. Visit and download Unzip and a folder named candidate should appear, with two additional folders inside named js and pix.  Drag the candidates folder into your mysite folder.
  2. Open the pix folder inside of candidates and take a look. You should see 21 small jpg images (yes 21!) of all the Republican and Democratic candidates for president of the United States in 2016.
  3. Use Brackets to open the candidates.js file inside of the js folder. You should see two arrays: candidateNames and candidatePix. One lists names, the other lists image names. Let's put those arrays to work!
  4. Create a new html file and save it into the candidates folder as (what else?) candidates.html. At the very bottom, just after </html>, connect candidates.js.

  5. For our first act, we are going to inject content from those arrays into a div tag. In order to do that, we need a div tag, so let's add a new one with an id of "alsoran" just after the <body> tag. 
  6. We will be working with both candidates.js and candidates.html simultaneously, so split your brackets editor vertically and open candidates.js on the right side.

  7. Create a variable named output and connect it to the alsoRan div tag with querySelector as shown below. 
  8. Now that the #alsoran id is connected to a variable, you can use the innerHtml method to add Jeb Bush to the #alsoRan div tag that it is associated with, as shown here.

     If everything is set up correctly, you should be able to preview candidates.html and summon Jeb.

    FYI: you could have skipped the previous step of defining the variable named output by simply using the statement:
    document.querySelector('#alsoRan').innerHTML=candidateNames[0];.  Although this method would work, it's not recommended because it's pretty clunky and other coders might make fun of you :-).

  9. Now that we have added the first candidate in the array, it is easy to add any of the others. For example, change candidateNames[0] to candidateNames[1] and Ben Carson will take the place of Jeb Bush. Or you could use the array.length property to insert the last candidate:

    The reason we subtracted one from candidateNames.length is because arrays are indexed starting at zero. There are 21 candidates but there is no candidateNames[21] candidate.

  10. Now that you know how to call the last candidate, Jim Webb, use the same method to call Donald Trump.

Putting images to work

We have images and an array that lists those images but how do we get those images to appear? The answer is simple: concatenation. When you concatenate you essentially 'stick' things such as text and variables together to create something new. It's quite easy to do once you understand the process. In this case we are going to pull string elements (the names of images) from candidatePix and stick them to some html code that will create a path to the image.

  1. Comment out the line that loads candidate names and add a new one below it that loads in the name of Jeb Bush's picture. When you test it, the letters bush.jpg should appear.

  2. bush.jpg is not very useful without the appropriate image tags so let's add them with concatenation, using the following screen capture as your guide.

  3. Did it work? Nope!  But why not? Might it have something to do with those images being inside of the pix folder?  Yes. To remedy that problem simply add pix/ after the = sign as in: Hopefully this time Jeb Bush's smiling face will appear. You could, of course, make the image appear by writing the html code yourself as in <img src="pix/bush.jpg"> which is exactly what Javascript does for you.

Now add the candidate's name as well.

The Kitchen Sink!

Now that we know how to painstakingly add one name and image at a time to out div tag, it's time to learn how to get all 21 of them to appear in a coherent fashion. For that task we are going to use a for loop. At this point, you may not be familiar with for loops, but they are a commonly used method to iterate through a set of data. In this case we will use a for loop to add each candidate's name and picture to our div tag, as well as the additional html needed to make them appear, well, however we want them to appear!

  1. As you can see, a for loop begins with the word 'for' followed by the structure of the loop. In this case our loop begins by creating a new variable named i with a value of 0.

    1. The next part, i < candidateNames.length, instructs the loop to continue to operate as long as i is less than the length of the candidateNames array.
    2. The last part, i++, increments the value of i by 1 each time that it loops.
      Hopefully, that explanation made sense!  Now it's time to use the screen capture as a model to build your own loop. Ie. copy it!
  2. The secret sauce that we need for the output of our loop is shown below in yet another screen capture.
    1. As you can see we have changed  output.innerHTML = to   output.innerHTML+ =. The purpose of the + sign is to cumulatively add content to the div tag each time the loop iterates. Without the + sign, the = sign would simply replace that content each time that it iterates.
    2. We have also replaced the 0 in candidateNames[0] candidatePix[0] with the variable i. Each time the loop iterates, i increases by 1, which means that it will place each candidate's name and picture into the div tag. We also added a couple of <br> tags in order to separate names, pictures and each candidate. So check it out.  Did it work? Ok, time for another step.
  3. Your job now is to create an ordered list of the candidates as in <ol> <li>. Hint. Among other things, you will need to change <div id="alsoRan"> to
    <ol id="alsoRan"> Good luck!
  4. Want to take things one step further? Good! Try setting up your Javascript and CSS so that div tags around each candidate's image and name, and images appear side by side rather than one after the other vertically

Build a calculator!

Free Code Camp is an excellent resource for learning basic Javascript concepts and techniques, but that learning becomes much more valuable when you put it to work inside of an actual html document. In this exercise we are going to build a crude calculator.

Before we go any further we need to fix a small problem with Brackets. For some reason, Brackets has a built in error finder that often cries wolf even when no long-toothed canines are anywhere in the vicinity. This can be pretty annoying so I simply disable this feature. To do the same,Go to Brackets > File > Extension Manager > Default > . Find EsLint and click disable. Then find JsLint and disable that as well. Errors be gone!

With that bit of housekeeping out of the way, let's get started by building ourselves a calculator. Obviously, we all have calculators at our disposal but this exercise isn't really about  math. The process of building your own calculator will actually teach you a lot about numeric and string variables in addition to a tiny bit about math.

Connect js to html and split the screen

  1. Create a new html document named calculate.html, a new javascript document named calculate.js and save both documents into a new folder named basicJavascript.
  2. Create a new folder inside of basicJavascript named js and move calculate.js into it.
  3. Connect calculate.js to calculate.html by typing  (type, don't paste) <script src="  after the </html> tag, browse to calculate.js (inside of the js folder), and connect it. Make sure that you close your script tag.

  4. At this point I recommend that you use Bracket's split screen option, and open calculate.html on one side and calculate.js on the other side.

Build the html document

  1. Let's start by adding a button between your the html page's body tags.   Give your button an id  of "addButton" and some text  between the tags that say add or something to that effect. Your button should look VERY similar to the one shown below.

  2. Next, add three input fields, using the screen capture below as a guide.

    At this point you have two number fields, one text field, and one button. Before we move on, a bit of formatting and labelling would be in order. You can make your own decisions on how to best present everything. The first two fields, input1 and input2 are for inputting numbers to be added. The third field, output, will ultimately show the sum of those numbers.  The purpose of the addButton should be obvious.

Javascript task one: identify the fields and buttons

In order to get information from your text fields and act on that information with the button, Javascript needs to know 'who they are' so to speak. We will accomplish this introduction via the querySelector method. You don't need to know too much about querySelector, but if you'd like to here's a quick definition. Basically, it means get the first element that matches what querySelector has in ().

Open calculate.js and on the first line enter the variable declarations shown below. The main thing for you to understand about this process is that you are creating new variables with the 'let' command, and are using document.querySelector to tie those new variables to the id(s) of your button and textfield elements.
The first line,
let input1 = document.querySelector('#input1'); , creates a variable named input1 that is equal to the textfield with the ID #input1, and the other three lines follow the same pattern.

Javascript task two: Create a function

Our next task is to come up with a way to get the values that are entered into input text fields, add them together, and then enter the sum into the output field. We will accomplish these tasks within a function and then call the function with the button.

The screen capture below shows one way to go about this task, still working in calculate.js.

  • On line one of the add function, a variable named addition1 is tied to the value of the input1 variable that was tied to the the #additionInput1 id in the previous step.
  • Line two works just like line one for the other input value.
  • Line three adds the two numbers from the text field
  • Line four places the sum value into the output text field.

Javascript task three: Call the function

Now that you have a function the next step is call it with the button. You might already know how to call a function directly from a button, as in
<button onclick="add()>, but this method is frowned upon in the serious Javascript community. The preferred method is shown below (we are still working with the calculate.js file). Here's more info about using .onclick.

Now test everything. Did it work? Did notice anything a little weird? For example, did the numbers concatenate instead of adding, as in 3 + 4 returns 34 instead of 7? The reason for that problem is that the values from your input fields are not numbers but "strings" or, in other words, text.

Javascript task 4: Convert strings to numbers

To convert those strings into text, follow the approach shown below in which Javascript's Number method is used to convert the value of input1 and input2 into numbers.

Oddly enough, even though the original input field was set to "number," Both your browser and Javascript still interpret its value as text (or string), and it must be converted to a number before it can be used for anything math related.

Let's break down this function a little more, shall we?

The word function simply means we are defining a function (not to be confused with calling a function, which is the instance you want to apply a function, in our case, we call our functions with the buttons). The word add is just the name of the function. If we were using parameters it'd go in the () next to add, but we're not using that for this function, so we leave that part blank. You have to have those (), blank or not, next to your function name. As mentioned previously in this lesson, let is a way to create new variables, so let addition1 is basically saying let's create a new variable called addition1, which is a number (not a string, AKA text) from whatever the input1.value is. Let sum is saying, let this new variable sum equal addition1 + addition2 (those variables we just defined). outputField.value = sum returns the variable sum in our output field.

If this doesn't quite make sense yet, don't worry. The more you work with functions, the more FCC you complete, the more they will make sense. And you're not done practicing with functions in this lesson yet!

Are you having trouble getting your numbers to add? Click the life preserver!

More Functions (and more buttons)!

Now that you know how, create three additional functions that divide, multiply and subtract the same values from the same fields. Then add and three additional buttons and use those buttons to call the three new functions. Once you finish, you should have a functional (albeit funky) calculator! For your sanity and mine, use the same output field.

Need a hint on how to get started? Let's start with the subtraction button. In your JS file, you'll need to write: let subButton = document.querySelector('#subButton');. subButton then becomes the id of the button in your HTML file. Back in your JS file, you'll need to define function sub — and you can reuse most of your script from your function add, except for perhaps the let sum line, right? That's the one with the actual math equation on it.... so maybe you just need to change the plus sign to the minus sign. Try to figure it out on your own! Remember, developers are lazy and we want to reuse as most code as possible.


Before we leave our lovely, powerful, impressive calculator behind, let's do one more thing. Imagine that it is a financial calculator, and we would like all of the values to appear with a $ (dollar sign) in front of them. Easy!  Just change the lines that say
outputField.value = sum;     to     outputField.value = "$"+sum; 

When you test your calculator again the dollar sign should be appended. Also, note the "$" is in quotes because it's a string. Concatenation (con+cat+uh+nation) is a fancy word which means to combine two values together.

If you wanted to make this calculator user-friendly and prettier, how would you do that? Perhaps with CSS, yes? Seeing how HTML, JS, and CSS all work together? We don't have time for that though, so let's continue with the JS stuff!


In an earlier lesson you were introduced to jqRotate.js, the add-on function that allows you to rotate elements in an html page. In the previous lesson, rotation was activated by mouse clicks. It is also possible to use the setInterval function to create a timed rotation, so that the rotation event re-occurs based on milliseconds. Why? With this function you can start a rotation that doesn't stop, such as a record player or the tires on a car.

The setInterval function is extremely to use In the example immediately below any action that you place between the { } brackets, will be executed every 2000 milliseconds (which is the same as every 2 seconds).

setInterval(function() {
 // Do something every 2 seconds
 }, 2000);

Jquery Rotation example with the jqrotate library

In the following setInterval function, a variable named howfar, that increments +5 (as in 5, 10, 15, etc.) every 800 milliseconds, controls the rotation of an element with the class "munk."  The same setInterval function can also be used to move elements in a straight or diagonal line by incrementing the x and/or y  values. By the way, the rotation shown below relies on the jqrotate library.

var howfar = 0;

Pure Javascript example with .transform

 var spinner = document.querySelector('#spinner');
var howfar = 0;  
 setInterval(function(){ howfar+=1; = "rotate("+howfar+"deg)"; },8);

Pulling music from Itunes

The jukebox assignment requires you to come up with a selection of music that your users can play. In Spring 2015 a student,Abemelek Markos, pointed me to the Itunes API as a source of 30 second song samples from the Itunes api. After fiddling with the api a bit, I came up with a form based method for finding 30 second Itunes samples.

To use the form, browse to, submit the name of a band, and you may get lucky. If, for example, you submit the word 'stones', you get links to 200 music samples of music by the rolling stones.  Each song comes with a player button and artwork. Each song also generates a url that says Copy this url as in
Copy This Url:

There are two ways that you can put a selection of these 30 second clips to use with your jukebox.

    1. Copy everything from http: to .m4a at the end and paste it into the appropriate spot in your music player.
       For example, you could take the code <audio autoplay="true"><source src="twist.mp3" type="audio/mpeg"></audio> and substitute twist.mp3 for
    2. Copy everything from http: to .m4a at the end, paste into your browser's address window, and 'save as' to download the song. BTW, it probably would be a good idea to shorten the name of the song a bit.
      You could also right-click on any of the album covers and 'copy image url' if you wanted to use that art in your jukebox.

Introduction to Ratchet

Ratchet is a web application prototyping tool that is sometimes used to test out design ideas via web browsers before committing a lot of time and resources to developing an actual native application. 1)Native applications run on your smartphone and often access the internet with need for a browser Unlike Bootstrap, which is designed to work screens of all sizes, Ratchet is strictly for the small screen. In fact, by default, it doesn't even respond to a mouse inside of a typical browser window, because it expects you to simulate a mobile device of some sort.  This may sound confusing but, as always, should make more sense once you experience Ratchet.


References   [ + ]

1. Native applications run on your smartphone and often access the internet with need for a browser

Randomized Youtube App

This lighthearted exercise doesn't require you to do much but it's kind of fun and offers a bit more information about arrays and php's 'random' feature.

1. Revisit Find the file named babies.php and click on it. A baby video should pop up from youtube. Like that baby? If not, click the button below to see a different, randomly generated, baby video.

2. Should you ever become tired of baby videos, download from, decompress it, and open babies.php with Brackets.

3. Take a look at the code. As you see, the whole thing begins with and array named babies, as in $babies = Array (, and there are lots of babies in that array. Each of those random collections of letters, symbols, and numbers, such as _JmA2ClUvUY, corresponds to a unique youtube video.   You could count them but php offers an easier way.

4. Take a look at line 15 where the variable $numberOfBabies = sizeof($babies); That's php for tell me how many baby videos are in that array.

5. On line 16 we actually take the variable $numberOfBabies and embed it into a sentence.

6. Take a look at line 18 where, for some odd reason, we subtract one from $numberOfBabies. The reason for this odd behavior is because we want to extract random numbers from the array that correspond to a given video but there is a problem: Arrays begin at 0, which means that even though there are 12 videos on that array, if the random number generator spits out 12, we have a problem. As far as that array is concerned, element 12 corresponds to the number 11.   Did that make sense?

7. Now take a look at line 21 where the random numbers are generated. This line, which reads,  $which= rand (0, $arrayNum);, generates a random number from 0 to whatever the value of $arrayNum happens to be. We could replace $arrayNum with 11 and everything would work just the same unless we add or subtract elements from the array. 

8. Lines 27 and 29 echo out the embed information that applies to all youtube videos, while line 26 grabs a random value from the array that corresponds to a given youtube video.

9. And that's it!  If you want to play a little bit, add those three extra baby videos on line 34 to the array and test it out on your server.

Next: Extras

Introduction to Databases (and mysql)

One of the main reason for PHP's popularity is that it plays well with a database system known as mysql. PHP and MYSQL underpin a huge portion of the web's content and many systems, such as WordPress, draw upon both. During the WordPress lesson a while back you were creating and storing data in a mysql database that served as content for your webpages. In this lesson you are going to learn how to interact directly with databases without a go-between framework such as WordPress.

The first step is to create a database. You already created one in the WordPress lesson even if you did an automated installation. Now we are about to do so once again.

  1. Browse to YOUR website and append cpanel to the url as in:
  2. Press return and click your way past any warnings that appear until you arrive at the cpanel login screen.
  3. Login with your username and password.Screen Shot 2015-03-23 at 12.11.18 AM
  4. Scroll down to the Database portion of the cpanel and click on the  MySQL Database Wizard. (Vintage icons pictured below).
  5. thisCreate a new database based on your username (the name you login to cpanel with) and append _db2 to the name as in emuel_db2. In other words, in the blank put in db2.
  6. Click the Next Step button and create a username. For simplicity, simply create a user with the same name as your database as in emuel_db2.  Next create a password for the database.  To protect your site from being hacked, I encourage you to create a STRONG password.
  7. Click Next Step, endow your new user with "all privileges" by checking that off at the top, and click Next Step again.

  8. You have created a new database and a new user, just like you did in the WordPress lesson but we have more work to do in the Cpanel, so click the home button to go there.
  9. Scroll back down to the Database portion of the cpanel and click the phpMyAdmin button. A new window should pop open which, on its left side, lists your two databases, as shown to the right.  Click on the _db2 database that you just created and look over to the right side of the page.

    That's where tables and data are displayed once you have some; which you don't at this point. Just for fun click on the other database that you created for the WordPress lesson. It should have LOTS of tables and data. Explore at bit if you want to. If you look hard enough you can find pages, posts, urls, and just about anything else that you have done with your WordPress site.

  10. OK, back to _db2. We could create tables and type data into them but for this lesson we are going to import pre-existing data. Create a new tab with your browser, visit, download and unzip it. One of the files that appears should be named candidates.sql. This file contains your data.
  11. Return to phpMyAdmin, click the import tab

    and then click choose file. Select arrowcandidates.sql (probably in your downloads folder) and click the Go button. After the smoke clears you should have a new table in your db2 database called candidates which is chock full of information about the 2012 presidential candidates.

  12. If the upload worked, skip to the next step. If, however, you clicked the go button and nothing happened you will need to take an alternate route in order to upload the data. You ONLY HAVE TO FOLLOW THESE STEPS IF THE PREVIOUS STEP FAILED.
    1. Return to and click on candidates.html. Select the first block of code under the heading Structure. This block begins with the words CREATE TABLE and ends with the word  latin1.
    2. Return to phpmyadmin, make sure that db2 is still sesqllected and click on the SQL tab. Paste the data into the the big empty text box that appears below, and click go. Once you get the Success message, delete the code that you just pasted in.
    3. Go back to candidates.html and select the final block of code that begins with INSERT INTO. Switch back to phpmyadmin, paste new block of code into the same big text box, and click go. Finally, your data should all be there! Now, you're caught up and ready to go on to the next step:
  13. Click on candidates and then on the Browse tab. You should see lots of riveting information about people such as Newt Gingrich, Michelle Bachmann, and Herman Cain. Now let's learn how to get that information to a web page.
    1. The first step is to establish a successful connection to the database. Once connected, you can start pulling data. Open connection.php (from the candidates folder that you just downloaded) with Brackets.

      This file, shown above, contains everything you need to connect. All you have to do is substitute the appropriate username, password, and database that you created earlier in the locations that are highlighted.In other words, if your username is john_db2, substitute john_db2 for "your_user_name". If your database is also named john_db2, substitute john_db2 for "your_database" and, of course, enter the password that you created earlier in place of "your_password". The only way to screw this up is to enter an incorrect value or to accidentally delete one of the quotation marks. So don't.

    2. Now take a look at the statements in this file. The first statement uses your username and password to establish a connection to the mysql server that holds your database(s) and ties the connection to a variable named, what else, $connection.  The next statement that starts with if (! connection)  checks to see if the connection was successful and alerts you if it was not successful. The next statement, starting with $db_select  chooses a specific database. The if statement that follows (once again) reports a failure if there was one. You can think of those if statements as tattletales.
    3. Login to your site with cyberduck and create a new folder inside of public_html called db. Upload connection.php into the db folder and visit it with your browser to see if it works. For example, if your website url was, you would browse to lianneharris/db/connection.php. If the page loads blank (aka zero content, aka white screen) and you don't get an error message, it works! Congratulations, time to move to the next step. If you do have an error, double check your username, password, and table to make sure that everything is correct re-upload connection.php and test it again.
    4. Find candidates.php, upload it to the db folder and check it out in your browser. All of the candidates first and last names should appear. Now, open candidates.php and let's take a look at how this minor miracle occurred.
    5. To begin with, look at line 2. 1)Which is actually the first line that actually does something. Line 2 has a require_once statement that loads connection.php, the file that you uploaded earlier. Without connection.php there is no (you guessed it) connection to the database. No connection no data. Line 3 "queries" the database, asks for everything in the candidates table (via the SELECT * command), and assigns that data to a variable named $get_data. $get_data, by the way is a totally arbitrary name. We could have named it $george, $gilbert, or $pinocchio and everything would work equally well.

      Line 4 checks to see if the query was successful and complains if it was not.
      Lines 5-7 2)I know, you're getting weary but it's about to get interesting :) are where the fun happens. The while statement creates a loop that doesn't end until all of the data has been placed into an array named $rows. 3)Once again, the name $row has no special powers. The next two lines instruct the browser to display all of the data in the first_name and last_name columns. The <br/> tag creates a line break after each candidate's first and last name appear. Note as well, the quotation marks ("    ") at the end of line 6 that create space between the first and last names to prevent them from being stuck together.

    6. This may feel like a lot to digest but at this point it's quite easy to get the rest of the data and display it on a webpage. Let's do it.
      1. From your ftp client (cyberduck perhaps?), click on candidates.php and open it with Brackets so that you can edit directly from the server.
      2. Remove ."<br/>" from the end of line 7. When you are finished the line should read like the following. Do NOT lose the semicolon!
      3.  echo $rows['last_name']; 
      4. Add a new line (on line 8) that reads:
         echo " was born in ".$rows[year_born]. "<br/>"; 

        As you may surmise, this line should add a sentence that states, for example, Mitt Romney was born in 1947, for each candidate. Save, upload, and test candidates.php again.

      5. Once you persuade your browser to state the candidates' age, it's time to add some of the additional data to your page. Remove ."<br/>" from the end of line 8 and add a new line that says:
        echo ", lives in ".$rows[state]. "<br/>";
      6. After you upload the file and browse it, the first line should read:
        Mitt Romney was born in 1947, lives in Massachusetts

        With similar lines for the rest of the candidates.

      7. Try this yourself. See if you can figure out how to add information about each candidate's spouse so that each line reads something like:
        Mitt Romney was born in 1947, lives in Massachusetts, and is married to Ann. 
      8. Now figure out how to display the remainder of the data so that each line in the browser also says (for example) He or she is a Republican Mormon, He or she is a libertarian Baptist, etc.
    7. That was fun (I hope), but what if you wanted to display data for just one candidate. Let's say that you are entranced by Newt Gingrich and want to know more about him, but only him. In that case you would use the SQL command WHERE to search for someone whose first name is Newt, last name is Gingrich, or both. Here's how it works: simply add WHERE first_name='Newt' to the query statement (line 3). In other words, modify line 3 to read:
      "SELECT * FROM candidates WHERE first_name='Newt'"

      Save candidates.php and upload it again. This time the browser should display only Newt Gingrich's information.

Requesting Data with a Form

So far we have focused on calling data via "hard coding"; ie. the data calls are written into the webpage. This method is fine for some purposes but what if you had a lot of data that you wanted to offer users the opportunity to request small pieces of data from a large database; a phone directory for example? A common way to resolve this issue is to create a form that can be used to submit requests to the database. Time to learn how.

Suppose that we want to make it possible for visitors to our website to query information by submitting a candidates's last name. Basically there are three steps:

  1. Create a form that submits a request to candidates.php.
  2. Insert a line of code that enables candidates.php to process the request and assign it to a variable.
  3. Change the SELECT WHERE statement in candidates.php so that it processes the value of the variable.
    1. Let's begin with the form. Create a new html page, and name it pick_one.html.
    2. Build your form. The text box below has everything you need to get started. As you can see, your form must have an action and a method (post is the most common). Take note that there are two form tags. A starting tag that begins with <form action and an ending tag that reads </form> . Everything that you do from this point forward must take place between those two tags.
      <form action="candidates.php" method="post">     </form>
    3. Begin by typing Last Name <input name="lastname" type="text"> between the form tags. Input name lastname is how the php document that receives the post will know how to identify the value. Text lets the form know that you want it to display a one line text box. 
    4. Now add a submit button by entering  <input type="submit" name="button" id="button" value="Submit"> When you are finished the complete form should look like this:
      <form action="candidates.php" method="post"> Last Name <input name="lastname" type="text"> 
      <input type="submit" name="button" id="button" value="Submit"></form>
    5. Save your document and return to candidates.php. Add this line of code to the TOP of your document, just below the <?php tag. It is important that this code go at the top of your document because it captures the posted value of lastname which it will use a bit farther down in the document to retrieve data for a specific candidate. 
      $lastname= $_POST["lastname"]; 

      FYI: the second part of this line $_POST["lastname, captures the lastname value from the form that you just created. $lastname is a brand new variable that provides a place to put the information from the form.

    6. Find the statement that begins with $get_data and change it to read:
      $get_data = mysqli_query("SELECT * FROM candidates WHERE last_name='$lastname'"

      Previously, we hard coded values so that WHERE last_name= '$lastname' would have read something like WHERE last_name= 'Obama' which would call the data for a specific candidate. This time, we want more flexibility so we have assigned that value to a variable.

    7. That's it. Save pick_one.html and upload it to the db folder. There is no need to upload candidates.php if you were editing it from the server. Browse to pick_one.html and pick a candidate by entering his or her name and clicking the submit button. Did it work? Great! Play a bit with the names of the various candidates.Just one more thing. Wouldn't it be great if we could offer users a way to select candidates without having to know their names by giving them a list of names that they merely have to click? Of course it would!  So let's do it.
    8. Go back to pick_one.html, and replace Last Name <input name="lastname" type="text"> with the code in the box below to create a radio group of icons. Be sure not to delete the submit button code.
       <input type="radio" name="lastname" value="Obama" id="lastname_0">
       <input type="radio" name="lastname" value="Romney" id="lastname_1">
       <input type="radio" name="lastname" value="Santorum" id="lastname_2">

      Follow the example and enter ALL candidates (name="lastname" value=" " is the important part). Once you are done, you will have a series of radio buttons with each candidates name listed
      beside it. Save pick_one.html and upload it again, unless you are editing directly from the server. If everything works properly you should be able to access the data for a given candidate simply by clicking their radio button and clicking submit.

Inserting Data from a Webpage

If you have ever registered for anything on the web, there is a high likelihood that you submitted data from a web-based form to a mysql database. The following exercise will show you how this is accomplished.

  1. The first step is to create a place to store the data. Return to your cpanel and login just as you did at the beginning of this php/mysql lesson, click on the phpmyadmin icon and then click on _db2 to bring up the same database that you have been working in.
  2. Click the New tab to create a new table. The table editor will appear with all kinds of confusing boxes and dropdown menus. As you can see there are lots of
    options when you create a mysql table. For now, keep it fanssimple and create your table named fans just like the one in the screen capture at right.
    After you are done, click Save. In case you are wondering, TYPE refers to the type of data that the field will be expected to store. In this case, we are storing mainly text data so we chose VARCHAR. You can also set the type to integer, date, text, and various other options. Length/Values refers to the character limit for a given row.
  3. Time to get started. Candidates.php contains some of the information that we will need to connect to the database so duplicate it and name the new file fans.php.  
  4. Now we will modify it. From your ftp client, open fans.php with brackets.
  5. Start by getting rid of what you don't need. Delete EVERYTHING after require_once("connection.php"); 4)leave that all the way down the the ?>. When you are done your document should look like this:
  6. Now let's do some surgery on pick_one.html.
    1. Duplicate pick_one.html and name the new file submit.html, change the form action in submit.html to fans.php instead of candidates.php. Go ahead and delete all of the inputs within your form EXCEPT your submit button. Next, you'll add 3 new labels with corresponding labels above your submit button. The code below can help guide you through this step...Wonder what the label tags are for? In your browser, try clicking the text, "Last Name:". If your code is correct, your cursor should jump to the corresponding text box to kick off the typing. Also, make sure that each iteration of "name =" is the same in your document. Save submit.php.
    2. Return to fans.php. The first step is to prepare this document to receive content from the form that you just created in submit.php. The good news is that you already have an example that you can expand on in line 2 where the statement $lastname= $_POST["lastname"]; is already set up to receive surnames. Simply copy and paste this line twice. Then, edit the two pasted lines so that they are equipped to call firstn. When you are done, your document should have 3 lines that look like the code below. Each of these lines assigns a variable of $lastname, $firstname, or $email to content that is posted to fans.php from submit.php.
      $lastname= $_POST["lastname"];
      $firstname= $_POST["firstname"];
      $email= $_POST["email"];
    3. The next step is to set things up properly so that the submitted content will end up in the fans table of the _db2 database. Simply copy and paste the following two lines of code 5)available in copycode.html at immediately below the line that says:
      $addfans="INSERT INTO fans (first_name, last_name, email)
      VALUES   ('$firstname','$lastname','$email')";

      Take a look at the code that you just pasted. The first line tells mysql to insert the values into the first_name, last_name and email columns that you created earlier. FYI: the $addfans variable is not strictly necessary but is quite useful because it creates a variable that can be tested to see if the insertion was successful. The second line, starting with VALUES tells mysql to insert the values for the three variables lastname, $firstname, and $email, that correspond to the data that was submitted. (whew)  Did you get that?

    4. The final piece in this puzzle is to add feedback so that your users can tell whether or not they submitted successfully. To accomplish this step, insert the code in the box below, just below the line of code you just added in step 3.
      if (!mysqli_query($connection, $addfans)) //checks for failure) 
      {  echo "this didn't work <br/><br/>";  //if failure, "this didn't work"
      die('Error: ' . mysqli_error());   }  //gives information about the error
      else { echo "1 record added. It worked!";}  //this one should be obvious :-)
    5. Once you are done, your entire document should read like this:
      $lastname= $_POST["lastname"];
      $firstname= $_POST["firstname"];
      $email= $_POST["email"];
      $addfans="INSERT INTO fans (first_name, last_name, email)
      if (!mysql_query($addfans,$connection)) {
       echo "this didn't work <br/><br/>";
       die('Error: ' . mysql_error()); }
       else {
      echo "1 record added";} 
    6. Once both documents are ready, submit some data. Did it work? If so, submit at least five more times, using a different first name, last name, and email address each time.
    7. Last step! Return to and download one more time. Unzip it, enter the folder that appears, and change the name of the newly downloaded candidates.php file to something like showfans.php.  Next, edit showfans.php so that it SELECTs the fans table instead of the candidates table. showfans.php at this point is already set up to pull data from the first_name and last_name columns of your DB. All you have to do is get read of the line that asks for the year_born column (which doesn't exist in the fans table) and replace it with a new line that pulls from the email column. EASY!

Next: Build a Map App

References   [ + ]

1. Which is actually the first line that actually does something.
2. I know, you're getting weary but it's about to get interesting :)
3. Once again, the name $row has no special powers.
4. leave that
5. available in copycode.html at