rotate

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

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

setInterval(function(){
 howfar+=5;
 $(".munk").rotate(howfar);},800);

 

 

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 http://familybutton.mynmi.net/submitsong.html, 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: http://a966.phobos.apple.com/us/r1000/048/Music4/v4/9a/90/da/9a90da79-5e24-84ee-1af2-6b0b01f71bf4/mzaf_894175191745970460.plus.aac.p.m4a

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 http://a966.phobos.apple.com/us/r1000/048/Music4/v4/9a/90/da/9a90da79-5e24-84ee-1af2-6b0b01f71bf4/mzaf_894175191745970460.plus.aac.p.m4a
    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 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.

 


  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 free.mynmi.net. 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 babies.zip from free.mynmi.net, 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 subdomain and append cpanel to the url as in:
    emuel.mynmi.net/cpanel
  2. Press return and click your way past any warnings that appear until you arrive at the cpanel login screen.
  3. Login with your new username and password.Screen Shot 2015-03-23 at 12.11.18 AM
  4. Find your way to the Database portion of the cpanel and click on the  MySQL Database Wizard.
  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.
  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", 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 s
    ide, 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 free.mynmi.net, download candidates.zip 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 free.mynmi.net 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!
  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 lets 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 in the candidates folder that you just downloaded with Brackets. codeThis file, shown at right, 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 lianneharris.com, 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 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.
      lines9Line 4 checks to see if the query was successful and complains if it was not.
      Lines 5-7 2 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 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 = mysql_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.
      <label>
       <input type="radio" name="lastname" value="Obama" id="lastname_0">
       Obama</label>
       <br>
       <label>
       <input type="radio" name="lastname" value="Romney" id="lastname_1">
       Romney</label>
       <br>
       <label>
       <input type="radio" name="lastname" value="Santorum" id="lastname_2">
       Santorum</label>

      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 save it as 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 all the way down the the ?>. When you are done your document should look like this:
    <?php 
    $lastname=$_POST["lastname"];
    require_once("connection.php"; 
    ?>
  6. Now let's do some surgery on pick_one.html.
    1. Duplicate pick_one.html and save it as submit.html, change the form action 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 immediately below the line that says:
      require_once("connection.php");
      $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 (!mysql_query($addfans,$connection)) //checks for failure) 
      {  echo "this didn't work <br/><br/>";  //if failure, "this didn't work"
      die('Error: ' . mysql_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:
      <?php
      $lastname= $_POST["lastname"];
      $firstname= $_POST["firstname"];
      $email= $_POST["email"];
      require_once("connection.php");
      $addfans="INSERT INTO fans (first_name, last_name, email)
      VALUES
      ('$firstname','$lastname','$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 free.mynmi.net and download candidates.zip 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


  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 free.mynmi.net

More PHP: Understanding Arrays

In our earlier PHP lesson we learned about variables. While variables are very useful for holding a single piece of data, there is a more effective solution for holding multiple related data elements: Arrays. So what are arrays? Think of arrays as sort of a "super variable" that can be used to store and extract vast amounts of information. Let's explore by revisiting our old friend variables.

Variables Again

Let's start our exploration of arrays with a refresher on variables.

1. Visit free.mynmi.net and download arrays.zip.

2. Unzip arrays.zip and upload the folder to your server.

3. From cyberduck, open the file called 1_variables.php with Brackets and look at the code. Inside of the php tags you should see a variable called $myname that is set to my (the author's) name and, immediately below, a line that says echo $myname;.

4. Substitute your name for Emuel, save the file and refresh it in your browser. Your name should appear.

As you probably have figured out, the variable $myname is set to the value of whatever your name is, and the echo statement tells the variable to display $myname. That's pretty much what variables do. They hold either string (as in names, phrases, etc.) or numeric data. The variable can be referenced to do something with the data such as displaying it, adding it to something else, etc. But what if you want to store several names at once. If you used variables you would have to come up with a cumbersome scheme such as $name1= "john"; $name2="Mary"; $name3="William"; etc. A much cleaner and easier way is to use an array; especially a basic kind of array which is known as a numeric array.

Numeric Arrays

Open the file named 2_basic_numeric_array.php and look at the code. Between the PHP tags you should see a line that states: $candidate= Array(); This statement creates an array named $candidate.

Now look at the subsequent lines that present presidential candidates from 2012 such as $candidate[0]="Mitt Romney"; $candidate[1]="Rick Santorum"; etc. The numbers that are associated with these lines 0,1,2,3,4 are used to reference the data.

Look further down to line 30 that states

echo $candidate[3];

Preview the file in your browser (your_domain_name/arrays/2_basic_numeric_array.php and the name Ron Paul should appear because he is the candidate referenced by the number 3. Change the number in the brackets to 4 as in

echo $candidate[4];

and Barack Obama will appear. Change 4 to 0 and Mitt Romney appears, etc.

Well that was simple (I hope). Now open 3_basic_numeric_array.php and look at its source code. This file shows the same $candidate array but this time one of the data points is tied to a variable named

$thecandidate as in $thecandidate=$candidate[4];

The next line echoes $thecandidate rather than specifically echoing $candidate[4] from the array but the outcome is the same.

Pulling data sequentially from an array

OK, it's about to get more exciting. Open 4_basic_numeric_array.php and take a peek at lines 30 through 32 as shown at right. This statement uses the foreach command to loop through the entire array and output the name of each candidate. On line 30 each component of the $candidate array is set to a variable named $whichone. Line 31 echoes a line break to separate values. Line 32 displays the actual variable on the screen, beginning with $candidate[0], Mitt Romney and ending with $candidate[4], Barack Obama. Browse to 4_basic_numeric_array.php to see the result.

Open yet another file called alternative_numeric_array.php with Brackets. This time viewing the file with your browser produces exactly the same result as the previous file, even though the array is set up differently.

$candidates=Array('Mitt Romney','Rick Santorum','Newt Gingrich','Ron Paul','Barack Obama') 

instead of something like

$candidate[0]="Mitt Romney"; $candidate[1]="Rick Santorum";

In both cases the function of the array is identical and it is a matter of personal preference as to which method you use. The first method of creating an array seems easier, but the second method (perhaps) presents the data more clearly.

Associative Arrays

Now that we have looked at numeric arrays it is time to visit another type known as associative arrays. Unlike numeric arrays which are indexed by numbers, associative arrays are indexed by by string variables such as names. Open 5_associative_array.php and take a look at the state array that presents each candidate's home state, indexed by their last names. As you see, the statement for outputting Obama's state to the browser is echo $state ['Obama'] instead of echo $state [4]. Substitute one of the other candidates for Obama and watch the display change. Almost too easy right? 

$state=array(
'Romney'=>'Massachusetts',
'Santorum'=>'Pennsylvania',
'Paul'=>'Texas',
'Obama'=>'Illinois');

//pull the data one piece at a time

echo $state['Obama'};

Now open 6_associative_array.php, look at lines 30 - 32, and test the file in live view. Once again the foreach statement is used to output all of the data in the array in the same way that it is used to output data from a numeric array. 

Multi-dimensional Arrays

Multi-dimensional arrays are used to store data that is more complex. The most useful and daunting characteristic of multi-dimensional arrays is that they are made up or arrays inside of arrays. Or arrays inside of arrays inside of arrays inside of arrays. You get the idea; they can be complicated.

Open 7_multidimensional_array.php and look at the array named $details, starting on line 25.

romney As you can see $details starts with the candidates' names which in turn lead to a series of associative arrays that contain information about each candidate's state, religion, year of birth, and the name of their spouse. At first glance this type of array can appear confusing but that's nothing compared to encountering this type of array when you are teasing data from the Facebook graph for example, because you can't even SEE all of the data or the embedded associative arrays. What do you do?  One word: var_dump.

Your friend var_dump

To see how var_dump works look at line 57 which asks for a var_dump of the entire $details array. Now click Live View to see what var_dump does. Confusing? Let's look at Romney's data and see if we can de-mystify this stuff a bit:

["Romney"]=> array(4) { ["state"]=> string(8) "Michigan" ["religion"]=> string(6) "Mormon" ["year_born"]=> string(4) "1947" ["spouse"]=> string(10) "Ann Romney" }

The initial statement ["Romney"]=> array(4) is trying to tell you that there are 4 separate data points associated with Romney: state, religion, year_born, and spouse. The statement ["state"]=> string(8) "Michigan" is telling you that state is an 8 character string variable which is, of course, Michigan. The same pattern applies for all of the other data; for example spouse is a 10 character string: Ann Romney.

So how do you get beyond the confusion of var_dump to discrete data that we can actually use? Let's start by commenting out the var_dump statement by placing two forward slashes in front as in:

//var_dump ($details);

Next, remove the slashes from //echo ($details), save the file and live view it again. Oddly enough, all you see is the word Array. That is telling you that you have reached a multi-dimensional array and have to dig deeper. Thanks to var_dump you have the tools to do so.

Place the slashes back on echo $details, on line 55, as in:

//echo $details; 

and de-comment

echo $details['Santorum'];

Once again, live view simply displays Array.

Let's dig one level deeper and de-comment the next line,
//echo $details['Santorum']['spouse']; Now we're getting somewhere. You should see Karen Santorum in live view. Substitute Obama or one of the other candidates for Santorum and you will see the name of their spouse. Or, as shown on line 61, substitute one of the other characteristics such as year_born to pull that specific data.

Experiment. Extract more details about Rick Santorum  such as his political party and the year he was born. Now do the same for at least one other candidate.

What if you wanted to pull all of the data about a specific characteristic such as religion or state? De-comment line 62 and check out the result. Feel free to play around and explore various aspects of extracting data from a multi-dimensional array. It can be a useful skill if you ever find yourself trying to extract data from a complicated api.

Next: Introduction to Databases (and my sql) 

Drag and Drop

You have already played around with the drag feature of jqueryui in the Mr. Potato Head lesson. This lesson features 'drop' functionality as well; ie. the ability to make something happen when one element such as a picture is dragged and 'dropped' onto another element.

This lesson will most likely have lots of detail and explanations in the future but, for now, it's more of an exploration and a chance for you to tinker.

Visit free.mynmi.net and download dropDemo.zip. Unzip the file, open drop.html in your browser and play around by dragging pictures to the 'drop here' div tag. Three of the pictures spark an audio file that says "wrong" while also changing the text that says drop here to Wrong!!. The 'wrong' pictures also skitter off to the right to make way for the next pictures.

The 'right' picture says 'correct', becomes partially transparent and also sparks an animation.

At this point your job is to use brackets to figure out how all of this takes place and to make some creative changes. The dropDemo folder contains images and audio files but the keys to this mystery live inside func.js, style.css, and drop.html.

One easy thing that you can do is add your own audio files to the folder and, inside of func.js, call your mp3 files instead of mine. Func.js is heavily commented so you should also be make changes that alter what happens to those pictures once they are dropped, the animation that is sparked on a correct drag, etc. And more.  Have fun!

Finally, if you want to use drag and drop functionality for your Jukebox project later on, I suggest that you download and take a look at dragsong.zip at http://free.mynmi.net.

PHP

PHP (which, oddly enough, stands for Hypertext Preprocessor) is what is known as a server-side scripting language. With html all the web server has to do is display the page. With PHP, the web server has to actually process the page and may have to do additional work before it can display the page. You, for example, write code that asks (in PHP language) the webpage to display your name. The server, which has PHP installed, interprets the code that you write and, if you wrote the code correctly, displays your name.

Getting started with PHP 

The only way to process a PHP file is via a web server that is properly set up to run PHP; ie. PHP files will not behave properly in a browser on your computer 1 so you will have to upload them to the server in order to see if they worked correctly or not.

PHP: Strings

  1. To begin, create a new html file with <head> <body> tags etc. and save it as intro.php.
  2. Click to the right of the <body> tag and press return a few times to create a work space. Now enter the following code to start a PHP segment:
     <?php 

    press return a few times and type

     ?>

    to end the segment. This is your work space. Everything you do in PHP has to take place between the <?PHP and ?> tags in order for the server to interpret your code.

  3. On the first line after <?PHP type echo "your name"; 2 The echo command tells the server to display whatever comes after it. The quotations are used because you are displaying a name instead of a number. Anytime you enter a word instead of a number you are entering what is known as a string. The semicolon is used to mark the end of a command statement. Without the semicolon you would get an error message.
  4. Save your file into your mysite folder as intro.php. Upload the file to your server and test it out. It worked? Great. If not, ask your instructor for assistance. Next, we will examine a new, and very important, concept known as variables.

Editing directly from the server

As you may have already figured out, it's a real pain to have to constantly re-upload a php file every time you need to test it.The solution to this problem is to edit the php file directly from the server. Here is how it works.

  1. Screen Shot 2015-03-19 at 12.20.19 PMOpen Cyberduck and click the preferences option shown here.
  2. Click the Editor tab and choose Brackets as your editor. Chances are you will have to browse to the Applications folder in order to choose Brackets.
  3. Click "Always Use this Application"  and close preferences.
  4. Find your way to intro.php and click gently on it just one time to select it. At this point the Brackets edit icon should appear as shown below. brack
  5. Click the edit icon and the online version of intro.php should open in a new Brackets window. Whenever you make changes to this version of intro.php and save it, the file on the server will automatically update. All you have to do to see the most recent results of your work is refresh intro.php with your browser.

 PHP: string variables

 

  1. Now that you have the server version of intro.php open in Brackets,  delete the echo "your name"; statement (ie. everything between the <?PHP and ?> tags. Add a new line that says
     $myname="your actual name"; 

    Congratulations you have just created a variable. Because $myname is tied to a word instead of a number, it is a type of variable known as a string variable.

  2. Now add a second line that says
     echo $myname; 3
  3. Save the file and test it by in your browser. Once again you should see your name. The difference is that this time your name is tied to a variable.
  4. Change $myname="your name"; to
     $myname="Mohammed Ali";

    Save and test again to see if the change took effect.

PHP: numeric variables

  1. Now let's play a little bit with numbers. Delete everything between <?PHP and ?> but leave some work space. Now type:
    echo 15*30;

    Save and upload the file again. The number 450, which is the product of 15 times 30 should appear.

  2. Delete echo 15*30; Now enter
  3. $firstnumber=15;
  4. and on another line
  5. $secondnumber=30;
  6. You have just created two numeric variables which behave like (not surprisingly) numbers. On a third line enter
  7. echo $firstnumber * $secondnumber;
  8. Saveand test everything once again. You should get the same answer as before.
  9. Modify the line that says echo $firstnumber * $secondnumber; to say $thirdnumber=$firstnumber * $secondnumber; This assigns the product of $firstnumber and $secondnumber to a new variable called $thirdnumber. Now echo echo $thirdnumber; and check your result.

Concatenation

You can do a number of useful things with strings, numbers, and variables and one of them is a process called concatenation which allows you to tie numbers, variables, and strings together. Concatenation sounds intimidating but the process is easy to conceive if you think of it as something like a lego set for sticking words, numbers and variables together into various combinations. In this case the "glue" is nothing more than a dot as in . symbol. Lets see how it works.

  1. While you still have those $firstnumber and $secondnumber variables let's put them to use. Delete the statement $thirdnumber=$firstnumber * $secondnumber; and replace it with this line:
    echo "The first number is ".$firstnumber.", while the second number is ".$secondnumber; 4

    What you are doing here is combining two phrases (strings) with the values of two variables to create a new, more complex statement. When you save and test you should see the following statement: The first number is 15, while the second number is 30.

  2. Change the values of $firstnumber and $secondnumber to something new and test again. The new numbers should appear in the statement.
  3. Your statements can also incorporate html code. For example, a string can include which will cause a line break when it is executed by the server. Lets try it by modifying the statement that you entered previously to say
    echo "The first number is ".$firstnumber."<br/>"; echo "while the second number is ".$secondnumber;

    When you test it this time the second statement should appear on a new line.

Loops

One of the most powerful features of PHP or any other scripting language is the ability to ability to execute a statement multiple times by using a technique called looping. There are several different types of loops but all have one important feature in common: they repeat an action (or statement) as many times as you tell them to. The example you are about to see is known as a while loop because it executes a statement as long as another statement is true. Enough talk, let's see an example.

  1. Delete everything between <?PHP and ?> and enter the code shown below.
    $loopnum=0; while ($loopnum<3) {echo "the current value of loopnum is ". $loopnum."<br/>";$loopnum++; }

    The first line initializes a new variable called $loopnum and sets its value to 0. $loopnum is how you will control your while loop. The subsequent lines perform the loop three times while the $loopnum variable is less than 3 and should produce the output shown at right. If you change the value in the line that states while ($loopnum<3) to a higher or lower number, the output will increase or decrease accordingly.

the current value of loopnum is 0
the current value of loopnum is 1
the current value of loopnum is 2

To summarize, loops are well worth knowing because they can save you a tremendous amount of work. We will revisit them later but, for now, it's most important for you to know that they exist.

Includes

Many websites built with PHP instead of html take a modular approach to building webpages via a feature called includes. Instead of one big file (as in html) that constitutes one webpage, pages constructed with PHP often are built "on the fly" out of multiple PHP files. 5

The beauty of this approach is that it works really well for updating a large website.  Includes allow you to store common features such as headers, footers, and links in individual files that are "included" (ie. shared) among all of the different pages of a website. Imagine, for example, that you create a series of pages that do not have links built into them.  How do you link all of the pages of your site together? Simple, you create one file that links to each of your site's pages and "include" it into each of the pages. Here's how it works:

1. Download includes.zip from free.mynmi.net and unzip it into your downloads folder (with Safari this happens automatically).

2. Use your ftp client (cyberduck most likely) to drag the includes folder into your public_html folder. 

3. Take a look in the folder. You should see five php files and one CSS file. 

4. Open one.php in your browser by browsing to whatever your domain is and appending includes/one.php as in emuel.com/includes/one.php. All you should see is a big red 1 and no links. Now open links.php in your browser. All you see there are links with no content. Let's change that and combine links.php with one.php by including it. 

5. Open one.php with your editor and look at the code.  Just below the body tag, type or paste in  <?php include 'links.php'; ?>. Save one.php and open it in your browser. It should now link successfully to two.php, three.php, four.php and itself. Problem is, none of the other files have links yet.

6. Open two.php, three.php, and four.php, and, once again, insert <?php include 'links.php'; ?> just below the body tag. 

7. Test everything again. This time all four files should be linked. 

8.Take this one step further. Open links.php and create a new link to http://cnn.com or some other website. Save links.php and test one.php etc. again in your browser. You should see the new link in all four files but you only changed ONE file: links.php. Even so, that new link to cnn appeared in all four files because you added to links.php which is now part of all four files. As you can see, this is an effective strategy for creating links to multiple pages without having to update the links multiple times every time you add or change a link. 

Next: More PHP. Understanding Arrays


  1. unless you set your computer to function as a de facto web server

  2. Don't be literal here, put in your actual name 🙂 

  3. Don't forget the semicolon.

  4. Make sure the quotation marks are exactly the same.

  5. You may have noticed this already while working through the WordPress lessons.