Learning Web Application Development With PHP and MySql

Recently, I enrolled in the Web Application Development with PHP and MySql course at diycomputerscience.com

The course is broken into four parts, where we start with an introduction to PHP, and end by making our own web application with PHP and MySql.

I just completed part 1, which is Introduction to PHP. I decided to pen my thoughts and notes below.

Part 1 of the course consisted of some learning material and 6 activities for practice. I started reading the book PHP and MySql Web Development, but soon realized that my natural style of learning is by doing and not by reading. So I decided to read just some basics from the PHP manual, and start doing the activities.

Activity 1:

The first activity was to create notes for PHP. I created this wiki page to record my PHP notes. I will continue to use this wiki page and add important facts, etc, which will make it a reference for me in the long run. More unorganized notes will be blogged on this blog.

Activity 2:

The second activity was to make a simple HelloWorld program in PHP. Here is the GIT commit for the activity.

My main learnings in this activity are:

  • A PHP script must be enclosed within special characters <?php .. ?>
  • We use the echo command to print something to the console or the browser
  • PHP strings can be single quoted as well as double quoted. Single quoted strings can contain double quotes, and double quoted strings can contain single quotes. Double quoted strings also support string interpolation.
  • We can run PHP scripts on the command line, but we need a utility for it.

 

Activity 3:

The third activity was to create a greeting page using PHP. Here is the GIT commit for the activity.

My main learnings in this activity are:

  • PHP has global variables which are available to the programmer for various tasks. One of the global variables is $_POST, which is an array containing all the post data (if the user made a POST request). PHP also provides us with _GET, and $_REQUEST
  • We use the '.' operator to concatenate Strings in PHP

 

Activity 4:

The fourth activity was to create a temperature conversion service, which will allow the user to enter temperature in either Fahrenheit, or Celcius, and the application would convert it to the other metric and display the result.

Here are two GIT commits I made for this activity. The first one accepts the temperature in Fahrenheit, and displays it in Celcius. The second one allows a user to enter the temperature in either metric, and displays it in the other. 

My main learnings in this activity are:

  • All variables in PHP are pre-pended with a $ sign
  • PHP arrays are actually key => value pairs. If we query the array for a non-existent key, we will get a NULL
  • PHP has support for the following types (Booleans, Integers, Floats, Strings, Arrays, Objects, Resources, and NULL)

 

Activity 5:

For the fifth activity we has to create a simple shopping cart using arrays. Here is the GIT commit

My main learnings for this activity are:

  • A PHP session has to be explicitly started with the session_start() command. I think there is a file setting which will create the session for us implicitly
  • We can include external PHP files using the include 'filename.php' statement. When we include an external file, it gets evaluated. I believe we can also use the require statement. I don't know the difference between the two, Need to find out.
  • session_unset will remove all the values which have been stored in the session
  • Most non boolean values will automatically evaluate to boolean when used in a conditional statement (need to figure out the exact rules)
  • In PHP we can iterate through an array using the foreach statement like this
    • foreach($array as $key => $value) {}
  • PHP supports the tertiary (cond ? something : something_else) operator
  • Comparison is done with the == operator. However PHP also has a === operator. Need to find out what it means.
  • PHP functions are declared thus:
    • function func_name ($param1, $param2) {}
    • We can have default parameters
    • We can have var args
  • Even though a PHP array consists of key value pairs, we can add an element to the array without specifying the key
    • $array[] = "new element";
    • In this case PHP will compute the key as 1 greater than the last numeric key
    • The key must be either Integers, or Strings
    • The gettype($var_name) function returns the type of a variable
    • The var_dump($var_name) function dumps all the details of a variable
    • The is_array($var_name) function will return a true if the specified variable is an array
    • We can find out the number of elements in an array, by using the count() function

 

Activity 6:

For the sixth activity we had to recreate the simple shopping cart using classes and objects. Here is the GIT commit for the activity.

My main learnings in this activity are:

  • PHP 5 onwards supports Object Oriented programming
  • We can create a class thus:
    • class ClassName {}
    • Need to find out if classes can be public, private, etc
    • Classes support public, private, and protected variables as expected. Need to find out, what is the default.
    • The class constructor has to be a function named __construct()
    • An object of a class is created using the new keyword.
    • Objects have access to the $this variable which will refer to the calling object. In most cases it is the object to which the function belongs, but in certain cases, it could also mean the object which calls the function. If the function is called statically, then $this will not be set.
    • Members of an object are accessed like $obj->member_name

 

 

Test Driven Development with JUnit 4.0 - week 2 activity 1

The first activity for this week is to create a test suite which will allow us to run all our unit tests together. JUnit 4.0 has an annotation @RunWith which let's us define a class in which we can declare all the test suites which willbe run when we run that test class.

I ceated a simple example for the two test cases which we have.

package practice;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses(
        {ComplexMoneyTest.class,
         MoneyTest.class}
)
public class AllTests {
   
}

Introduction to Javascript for programmers - week 1 activity 2

Activity 2 for week 1 is to create a simple HTML page which contains a Javascript snippet which would pop up a 'Hello World' alert.

 

Test Driven Development with JUnit 4.0 - week 1 homework 2

This is for activity 2 of the Test Driven Development with Junit 4.0 course.

 

 

Filed under  //   diycs-sg1   junit   

Test Driven Development with JUnit 4.0

I have enrolled in an online Study Group on Test Driven Development with JUnit 4.0 on diycomputerscience.com

The first homework activity is to write a unit test for a Money class. See activity 1 on the course page for week 1.

I recorded my desktop as I did the homework...

 

 

Filed under  //   diycs-sg1   junit   

Video : Javascript from the bottom up - My Notes

The first video to watch for week 1 is this video from Google HTML/CSS/Javascript from the ground up. My notes follow (along with the timeline in the video):

00:00 Introduction

Javascript helps make our webpages interactive. Things like validating forms, drag & drop, hiding and showing elements, changing the color of certain elements and so on.


01:13 Getting Javascript into your webpage
There are various ways by which we can include Javascript in our web pages.

  • Inline - though this is a bad idea
  • Embedded Javascript <SCRIPT> tag
  • Including a reference to a Javascript source file

The following code is an example of inline Javascript (someFunc() is a Javascript function probably defined elsewhere in the HTML file):

<div onmouseover="someFunc()">

We should avoid such inline usage of Javascript because it mixed presentation and logic... which is always a bad idea from a maintenance perspective.

A better way is to embed all your Javascript in <SCRIPT> </SCRIPT> tags, and then have an init function at the end of the page which adds event listeners, which in turn call certain functions when the event listener is invoked. We have not discussed event listeners, so I will not provide an example here.

The third way of including Javascript is to reference an external file which contains all the Javascript functions. In the line below, we include JQuery's external file containing it's Javascript code.

<script type="text/javascript" language="javascript" src="/public/javascripts/jquery-1.4.2.min.js">
</script>

Out of all the above ways, the third is the most preferable way of including Javascript in your web page.


03:10 What can we do with Javascript

Now that we know how to include Javascript in an HTML page, the next question that comes to mind, is what can we do with Javascript?
Many people confuse Javascript for Java, so it is wise to remember that Javascript != Java. Even though Javascript is not Java, it has all the basic features of programming.

04:04 Basic syntax

var foo = 7; //valriables
var baz = 4 + (3 * 2) //operators
var baz = 'a string'; //Strings
var arr = [1,2,3]; //arrays
var f = function(x, y) { //functions
    return x * y;
}
if(baz) {} //conditionals
while(i < 4) {} //while loop
for(var i=0; i<10; i++) {} //for loop

JavaScript is an object oriented programming language... objects can contain properties and functions (called methods). They are good at helping us organize our code.

05:42 How does Javascript interact with web pages

We said earlier that Javascript interacts with web pages. It does so through the DOM (Document Object Model). It (DOM) represents the HTML document as a tree of objects, such that we can manipulate these objects with Javascript code.

HTML elements -> node object (in the DOM)
Attributes of HTML elements -> property of the node object

Here is a blog post which shows the Javascript objects which represent the DOM.

In Javascript, the DOM is represented as a tree of Javascript objects. These objects expose properties to us and we can manipulate those properties to change the look and feel of the web page.         

To manipulate the elements, we first need to obtain a reference to them. We can get a reference either using the id of the element, or it's tag name. Let's use the following HTML as an example:

<div id="about">
   <p id="first"></a><p id="second"></a>
</div>

document.getElementById('about'); //get the node object of an element which has a specific id
document.getElementByTagName('p'); //will return all <p> nodes
//we can even chain these
document.getElementById('about').getElementsByTagName('p');

Javascript by itself gives us just these two methods of selecting a DOM node. However, it would be wonderful if we could access elements by their CSS classname, or in a way that CSS selectors do. Well it seems, we cannot do this directly in Javascript, but we can use 3rd party libraries, like JQuery, or one of many other libraries to do it. Some such libraries are listed at http://getelementsby.com

Once we have a reference to a DOM element, we can access those elements to which our element has a pointer to. A DOM element has pointers to it's parent, children, and siblings:

p.parentNode
p.childNodes //array
p.firstChild
p.lastChild
p.previousSibling
p.nextSibling

Something we should be aware of is that a browser parses the HTML page from top to bottom, and parses (and if possible executes) the Javascript as it encounters it.


10:56 What can we do with DOM elements
       
We can attach listeners to DOM events which are generated on DOM elements, so we can do something special when a user interacts with that element.

Some events:

  • click
  • mouseover
  • mouseout
  • mousedown
  • mouseup
  • blur
  • focus
  • load


Unfortunately, the way in which we attach listeners is different for IE and other browsers.

On IE we should use:
selectedElement.attachEvent('onclick', handlingFunction); //IE

and on all other browsers, we should use:
selectedElement.addEventListener('click', handlingFunction, false); //All other browsers

So how do we know which to use?
Bad Idea: Javascript will allow us to check which browser is being used, and based on that we can decode which function to call.
Good Idea: Use object detection ... check if the object has a certain property

if(selectedElement,attachEvent) {
  selectedElement.attachEvent('onclick', handlingFunction); //IE
} else {
  selectedElement.addEventListener('click', handlingFunction, false); //All other browsers
}
       
13:41 What can we do with the events after attaching listeners

Change the look of your page, change CSS styles, add elements, remore elements... REVIEW
Don't mix presentation and behaviour... manipulate class names of elements... be careful and don't remove existing classes of elements...

16:30 Default events

preventDefault() function allows us to prevent the browser from performing the default behavior.

Introduction to Javascript for programmers

I signed up for participation in the Introduction To Javascript (for programmers) course on diycomputerscience.com

In week 1, we are supposed to watch a video which explains the basic capabilities of Javascript in about 17 minutes, and then do 2 learning activities. The first week seems like a relatively low pressure week.

I will be blogging my notes for every video on this blog, and will also publish assignments and activities here.

Filed under  //   diycs_sg2   javascript  

Javascript 101 - Week 5 Assignment 2

Write the convenient function removeElement which removes the DOM node it is given as an argument from its parent node.

 

 

Click here to see the solution in full screen on JSFiddle

Javascript 101 - Week 5 Assignment 1

Write a function asHTML which, when given a DOM node, produces a string representing the HTML text for that node and its children. You may ignore attributes, just show nodes as <nodename>. The escapeHTML function from chapter 10 is available to properly escape the content of text nodes.

 

 

 

 

Click here to see the solution in full screen

Javascript 101 - Week 5 Questions for reflection

1. Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?
Sometimes we have a scenario where there may be several (hundreds or thousands) of child elements. Let's assume these are image elements which have to support drag and drop. Now if we add an event listener to all these elements then the web page may get really huge (because of the onEvent="someJavascript()") code in each element. To prevent such code bloat, we may attach the event handler to the parent element of all these elements. By doing this we get away with just one event handler which will handle the event for all the child elements. However, this will work only of the event get's bubbled or tricked, enabling it to be dealt with by the parent. Normally we prefer bubbling of events, becasue MS does not support the trickling model, so it's better we stick with the bubbling model which is supported by all web browsers.
2. Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this?
We may want to prevent the browser from submitting a form, if the form fields do not have correct data. We often employ Javascript for client side validations of form data. The validation happens on the client side, and the form is submitted only if the form data is successfully validated.

About

I am an freelance software developer and trainer. I am also interested in open education and social learning. This Posterous is my experiment in getting an equivalent of a masters education in Computer Science using open courseware and social learning.