31 May 2012

CMT3313 - Week 12 Post - Virtual Learning

In this week's post I'm going to write about Virtual Learning and how we can improve this to make it more realistic and effective, both for learning and for costs.


I shall start off with the advantages of virtual learning. So, the most obvious advantage is location, I am currently enrolled in a Middlesex University Degree, but I attend my lectures in Malta at STC, where I receive my lectures by tutors employed by STC, which have to follow strict rules on what to teach us from module leaders employed by Middlesex University, which are also based abroad. 


Now take a moment to think about all this, Middlesex University employs module leaders (which are basically tutors), STC employs other tutors, students pay STC for Middlesex University's course, plus administration charges and tutor wages. Exams are done using a pen and paper, corrected by STC's tutors, shipped to Middlesex University and corrected once again by their moderators. Those moderators have to be based in Middlesex University's campus, thus if they are from a foreign country, they must have left their families behind to work there...see where I'm going?


Virtual learning could simplify this system tremendously by first of all cutting out the middleman, that's STC...sorry I don't mean to put you guys out of business, but in my opinion this is the way forward. Next, students would interact directly with Middlesex University's tutors, while staying in their own country, same goes for the foreign tutors. Middlesex University would also gain from this as it would not have to cater for so many employees in one location, therefore making it possible to operate from a smaller premises.


All of these facts would cut cost tremendously and improve practicality as students and tutors would communicate directly while staying in their native countries...But for this system to be efficient, some things still have to be improved as I will now explain by covering four technologies which will lead to my proposal.


Video Lectures
These are nowhere near virtual learning, but its been practised for a number of years now. It consists of a tutor recording a lecture, this recording is either live steamed to students around the world or made available for download to view at a later stage. This alone solves the location problem I mentioned earlier, but it lacks an important attribute...INTERACTION!!
Students & tutors cannot interact freely this way, sure some kind of instant messaging system can be used but this is not very convenient as it could be hard to express one's self through writing.


Google Chat
To overcome this problem in one of our lectures we tried an experiment in class, in which we used Google Chat to communicate via our devices' web cams and microphones. This enabled each student to see the lecturer and the lecturer could see every student, but this method had a problem as when one of us spoke, his voice was being picked up by more than one microphone, resulting to echoing. True, we were all standing in the same room but even if we were all in separate locations, the sound coming out of out speakers would have had the same effect. 
Therefore this method was a complete failure without the use of specialised hardware for the job.


Second Life
This is a 3D world where every user has his/her own avatar and can roam around these fictional or quite realistic in some cases, locations. I am planning to dedicate a post for Second Life in the near future, but today I will only mention when we tried to carry out a lecture in it. We all decided to visit Middlesex University's virtual location and meet up in a Greek theatre sort of place, where we all sat down and looked at the lecturer. But for interaction , Second Life offers a chat box and this takes us back to the problem I mentioned with video learning, plus I found the power which second life gives you quite distracting, as in Second Life you can build your own objects and this led to someone building a huge wall which completely blocked off the lecturer from the rest of the class (Although I must admit it was quite funny).


Real Telepresence
After doing some research I stumbled upon the following video of a Black Eyed Peas concert where two of the singers where life-size holograms being projected to the audience. 

This sparked my interest, as if these guys managed to do this in a concert, there must be a way to use this technology in a classroom setup and after I carried out a bit more research I discovered Real Telepresence.

The DVE immersion room, to be more precise! This makes use of hologram technology to create impressive realistic conference rooms where you can see the other party crystal clear, see every non-verbal communication, make eye contact and hear them as if they were standing in the same room.


My Proposal
This got me thinking, what if you could hook up these systems together to allow more than two locations in one large group?
Students in multiple countries would go into their local DVE immersion room, (Note to STC: If this idea ever picks up, you can always provide these local DVE immersion rooms) which would have holograms projected on the side as well to show their "immersion room class mates" in order to give them the feel that they entered a large lecture room and the tutor would see all these immersion rooms located in different countries combined as one. The images below illustrate my proposal.

Bird's Eye View

Tutor's View

16 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 6

Welcome to the final blog about coursework 2! I have completed all the required coding, so know I am going to post about the last two functions of my game, which are:


  • Score Keeping
  • User Notifications
In my 3rd post on this coursework I had shown you the structure of my users table, which consisted of two particular fields; Score and Last_Beat_By. The use of these fields will be explained in this post.



Users table structure


Score Keeping Functionality
So now, to make any game that bit more exiting, it must have some sort of scoring, not only that but scoring is also the unit of measure when users want to compete against each other!
Therefore I was time add this all important scoring functionality to my game and I came up with the following list of things I had to include:

  • Set up the rules of how points are given or taken
  • Accumulate on user's latest score
  • Save the score once the user ends the game
  • Display a Score Board at the end
Scoring Rules:
I decided to make the user able to increase as well as decrease his/her latest score and to do so I decided on the following way of how this would apply.


Accumulate Latest Score:
For a user to continue improving...or ruining his/her latest score, it had to be queried from the database and stored in memory. This task is handled during user authentication, as when I query for the user's record, I store the user's score in a session variable via PHP, along with other details such as the Last_Beat_By:

function authUser($userID, $password) {

    $authUserSQL = "SELECT * FROM users WHERE USER_NAME = '" . $userID . "' AND USER_PASSWORD = '" . $password . "'";
    //queries the database for the user record with the received parameters.
    $result = execute($authUserSQL);

    if (mysql_num_rows($result) > 0) {//record found
        $record = mysql_fetch_array($result, MYSQLI_ASSOC);//stores the returned result in an associative array
        //stores user's related data in session variables
        $_SESSION['userName'] = $record['USER_FULL_NAME'];
        $_SESSION['highScore'] = $record['SCORE'];
        $_SESSION['lastBeatenBy'] = $record['LAST_BEAT_BY'];
        $_SESSION['userID'] = $record['USER_NAME'];
        $_SESSION['Authenticated'] = "yes";
        return TRUE;
    } else {//no record found
        return FALSE;
    }
}


Score Keeping with JavaScript:
After this is done the user gets redirected to the game. To avoid having to retrieve the session variables via JavaScript, I output the session variables to JavaScript variables using PHP as shown below:

<html>
 <head>
   <title>Paper Toss Game</title>
   <script type="text/javascript">
    <?php echo "var userName = '" . $_SESSION['userName'] . "';"; ?>
    <?php echo "var origScore = " . $_SESSION['highScore'] . ";"; ?>
    <?php echo "var lastBeatenBy = '" . $_SESSION['lastBeatenBy'] . "';"; ?>
    <?php echo "var userID = '" . $_SESSION['userID'] . "';"; ?>
    var newScore = origScore;//running score counter
    var myPaper;//the paper object (image)
    var myBin;//the bin object (image)
    var binXLocation;
    var ammo1XLocation;


Once the paper toss page is sent to the client, the variables which are outputted by PHP will look exactly like all the other variables, therefore keeping in mind that JavaScript is a client side technology, I can reference these variables normally.
Back to score keeping, in the above code you can see I am storing the retrieved score in a variable name 'origScore' and then storing this variable in another, named 'newScore'. This is because at the end of the game I want to  know what was the user's score at the beginning. I will explain later when I cover the user notifications function.


Now that I have the user's latest score in memory on the client side, all I have to do is increment or decrement this value according to where the paper ball lands, for example:

        if(paperYLoc>=-150 && paperXLoc>binXLocation){//dunk
            clearInterval(landMotion);
            newScore = newScore + 20;
            alert("Dunk! YOU WIN!!!  +20 points");
        }else if(paperYLoc<-150 && paperXLoc>binXLocation){//overshoot
            clearInterval(landMotion);
            newScore = newScore - 5;
            alert("Over Shoot!  -5 points!!");
        }else if(paperYLoc>=-20){//not far enough
            clearInterval(landMotion);
            newScore = newScore - 10;
            alert("Not far enough!  -10 points!!");
        }
Saving the latest score:
Once the user clicks on the 'End Game' button at the bottom, he/she gets redirected to another page named 'saveGame.php' and the required values are posted to this PHP file just like I explained in post 4 of coursework 2.
Once the request passes the verification that it's an authorised one, a function gets called which updates the user's record with the latest score.


function saveScore($userID, $score){
    $updateScoreSQL = "UPDATE users SET SCORE = ".$score.", LAST_BEAT_BY='' WHERE USER_NAME = '".$userID."'";
    $result = execute($updateScoreSQL);
    return $result;
}


This function returns the a boolean which states whether the update was a success or not.
If the update was successful the user gets redirected once more to a page called 'scoreBoard.php'


The Score Board:


<?php
    $rowCount = 0;
    $result = execute("SELECT USER_NAME, USER_FULL_NAME, SCORE FROM users ORDER BY SCORE DESC, DATE_JOINED");

    //loop through all the returned records and create a table row for each
    while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
       $rowCount = $rowCount + 1;
       if ($row['USER_NAME'] == $_SESSION['userID']) {
          //Use the echo to output HTML code with the retrieved data
          echo "<tr>";
          echo "<td align=\"center\" style=\"color: #FF0000\">" . $rowCount . "</td>";
          echo "<td align=\"center\" style=\"color: #FF0000\">" . $row['USER_FULL_NAME'] . "</td>";
          echo "<td align=\"center\" style=\"color: #FF0000\">" . $row['SCORE'] . "</td>";
          echo "</tr>";
       } else {
          //Use the echo to output HTML code with the retrieved data
          echo "<tr>";
          echo "<td align=\"center\">" . $rowCount . "</td>";
          echo "<td align=\"center\">" . $row['USER_FULL_NAME'] . "</td>";
          echo "<td align=\"center\">" . $row['SCORE'] . "</td>";
          echo "</tr>";
       }
    }
?>


Once this page is requested, before sending it to the client-side, PHP code is run on the server, which queries for all the names and their respective score and outputs the appropriate HTML code to build dynamic table rows in order to create the score board.
A small touch I decided to include is a check for the current user's record and highlight it in red font. The screen shot below illustrates this score board.



Notifications Function
I decided I wanted to fuel up a little bit the competitiveness between the players, therefore I wanted to display a notification upon logging in, which tells the user if a player beat his last score while he/she was away.
In the previous section I already mentioned where I am storing this value in the table and how I am retrieving it, so I am going to skip that part and move on to when I populate this value and display the notification.


Keeping track of who beat who's latest score:
I previously said that, once a user clicks on 'End Game' his/her score is saved and the  score board is displayed, well...I what I didn't say is that between those two actions lies something else. After saving the user's score an IF statement checks if the user's original score, stored in 'origScore' which I already mentioned, is less that the new score. If this is the case, I call a function named 'updateBeatenUsers()' which updates all the user records which had their score beaten by this player, with the player's full name in the Last_Beat_By field.


function updateBeatenUsers($userName, $origScore, $newScore){
  $beatenSQL = "UPDATE users SET LAST_BEAT_BY = '".$userName."' WHERE SCORE >= ".$origScore." AND SCORE < ".$newScore."";
  $result = execute($beatenSQL);
  return $result;
}


Displaying the Notification
Now that I am keeping track of who is beating who's score, all I need to do is notify the user on first login. This part is quite easy as once the user is redirected to the game page I have a variable representing the Last_Beat_Value (I explained this in the "Score Keeping with JavaScript" section), therefore its a simple matter of checking whether or not the variable contains a value and if so, display it in a JavaScript alert box like so:



After this, I reset the user's Last_Beat_By field back to null during the saving of the score so that this message will not get displayed the second time the user logs on.

Conclusion
So know, that's the last of this coursework, I must say that its been quite a learning curve but I enjoyed it as I got an exposure over a range of web technologies and managed to create a simple game with a social aspect, which by the way I could host online and have my friends join in!

I hope that my experience was of some use for you who read these blog posts and I would like to say, feel free to comment on my work.

Now, if you excuse me...I've got another round of paper toss to attend to, see you!!

15 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 5

Hi there, I'm currently working full blast on coursework 2 and I have finished implementing and testing the 'Sign Up' and 'Remember Me' functions which I had mentioned in my third post on this subject. Therefore I will cover these two function in today's post.


Sign Up Function
Lest start off with taking into consideration new joiners who don't yet have a profile, hence don't have any login details to access the game. For this I created  another page with the required fields the user must fill in and it looks something like this:
Sign Up Form
It's not the prettiest interface, but I'm not really giving much attention to eye candy as I am more interested in the functionality aspect of this project. This situation reminds me of an infographic I saw a while back so I decided to include it in this post :)
Designers VS Developers
So, back to the sign up screen. Validation is pretty much handled the same way as in the login screen, apart from comparing the two password fields to make sure they are the same, therefore I will not go into detail again and stick to what is most interesting.
In this form the user is required to insert a User Login which is essential for it to be unique as he/she will use this as part of their login details. But what if the new user coincidently inputs a user login which is already taken?
I address this issue once the user clicks on the create button, which I will now explain.

Once the create button is clicked a JavaScript function which validates the user input is called and if the validation is a success, this function will call another function named 'redirect()'. Yes you guessed it, this function does the same thing as the one I described in my previous post, but instead sends the full name, user login and the first password field values to another PHP page which I've named 'createNewUser()'.

createNewUser.php:
    
<?php
session_start();

include 'DBConnections.php';

if (isset($_POST['fullName']) && isset($_POST['userID']) && isset($_POST['password'])) {
    $UserID = strtolower($_POST['userID']);

    //check if passed userID is available
    if (mysql_num_rows(checkUserIDAvailability($UserID)) == 0) {//available
        //create new user
        $createUserSQL = "INSERT INTO users (USER_FULL_NAME,USER_NAME,USER_PASSWORD) VALUES('" . $_POST['fullName'] . "','" . $UserID . "','" . $_POST['password'] . "')";
        if (execute($createUserSQL)) {//executes the insert and if true is returned, continues
            //stores user's related data in session variables
            $_SESSION['userName'] = $_POST['fullName'];
            $_SESSION['highScore'] = "0";//by default this is always zero
            $_SESSION['lastBeatenBy'] = "";
            $_SESSION['userID'] = $UserID;
            $_SESSION['Authenticated'] = "yes";

            //redirects to paper toss
            header("Location: PaperToss/paperToss.php");
        }
    } else {// not available
        $_SESSION['error'] = "This User Login is already taken, please input another one";
        $_SESSION['fullName'] = $_POST['fullName'];
        header("Location: signUp.php"); //redirects to signUp
    }
} else {
    header("Location: signUp.php"); //redirects to signUp
}


function checkUserIDAvailability($UserID) {
    $result = execute("SELECT * FROM USERS WHERE USER_NAME = '" . $UserID . "'");
    return $result;
}
?>


Code Breakdown:
As soon as this page is requested, it it makes sure that the session is started and includes the DBConnections.php file I created in my third post on this subject. Then it immediately verifies that the required variables have been posted. Otherwise this request must have been made manually, not via the create button, so it redirects to the sign up page.


If all the variables have been posted, it moves on the check if the user login is available. This is done by calling the function 'checkUserIDAvailability()' which can be seen at the lower end of the code above.
This function makes use of the DBConnections.php 'execute()' function and queries for a record from the users table which has the same user login ($UserID) value. The returned resultset is then stored in '$result' and returns it to the calling statement:

function checkUserIDAvailability($UserID) {
if (mysql_num_rows(checkUserIDAvailability($UserID)) == 0) {//available
    //create new user record   
} else {// not available
    //redirect back to sign up
}


The calling statement is placed in the function 'mysql_num_rows()', this function will return the amount of records present in a resultset, therefore if the row count is not zero, the user login must already be taken, otherwise the  user login is available.


function checkUserIDAvailability($UserID) {
    $result = execute("SELECT * FROM USERS WHERE USER_NAME = '" . $UserID . "'");
    return $result;
}


In case the user login supplied is not available, a session variable named 'error' is created and an explanatory message of what happened is stored in this session variable, this will be used by the sign up page to display to the user. 
Apart from that another session variable named 'fullName' is created and stores the full name the user inputted, this session variable will also be used by the sign up page to populate the Full Name field, so the user will not have to type it again. Finally the user is redirected back to the sign up and the message gets displayed in red:
Sign up page when user login is already taken
On the other hand if the user login is available, crates a new record in the users table with the inputted details:



    
//create new user
$createUserSQL = "INSERT INTO users (USER_FULL_NAME,USER_NAME,USER_PASSWORD) VALUES('" . $_POST['fullName'] . "','" . $UserID . "','" . $_POST['password'] . "')";
//executes the insert and if true is returned, creates required Session 
//variables & redirects to game.
if (execute($createUserSQL)) {
   //stores user's related data in session variables
   $_SESSION['userName'] = $_POST['fullName'];
   $_SESSION['highScore'] = "0";//by default this is always zero
   $_SESSION['lastBeatenBy'] = "";
   $_SESSION['userID'] = $UserID;
   $_SESSION['Authenticated'] = "yes";

   //redirects to paper toss
   header("Location: PaperToss/paperToss.php");
}


After executing the statement, checks if the insert was a success. If so the requires session variables are created and the user is redirected to the game.


Remember Me Function
So, up till now I have only used Session variables and as I have stated before, these are temporary. Therefore to implement a Remember Me function I had to use Cookie variables, as these will be stored on the user's machine and sent along with the request when the user visits my game.
To implement the use of cookies I made the authentication.php page receive an extra variable for the checkbox element.
Once a user is authenticated, if the checkbox value is equal to true I create two cookie variables, one for the login and one for the password and set their value accordingly.
  
if($_POST['rememberMe'] == true){
   setcookie("UserID", $_SESSION['userID']);
   setcookie("UserPW", $_SESSION['userPW']);
}


In the index page (i.e. - the login page), I added a check using PHP code to populate the user login and password fields if the above cookies are sent to the server side:

<?php
//if the user password is set in a cookie, populate the Password field
echo "<input type=\"password\" name=\"password\" title=\"Password\"value=\"";
if (isset($_COOKIE['UserPW'])) {
    echo $_COOKIE['UserPW'];
}
echo "\"/>";
?>


Paper Toss Game Progress
So now, as a recap, my paper tossing game has a fully functional user sign up and login with remember me functionality, thus the task of transforming coursework 1 into a social networking game is taking shape.
By the way do you remember in my previous posts I mentioned that I gave my  game a nice background of a cheering crowd? Well I got in touch with the owner of that image to request permission to use it and, well...he charged me $49 for it. Unfortunately I am not ready to pay that sum of money for a detail of such little importance, therefore to respect others property I changed the background image to an un-copyrighted image, so now it looks like this:


Un-copyrighted background image


14 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 4

Today I will re-visit the way I am redirecting from one page to the other, because if you remember in my first post on coursework 2 I was the form to call another page on submit and pass it some values via the POST method and I wasn't quit happy with it as I wanted to validate the user input only on the client-side and redirect to the next page once the validation was successful. In reality this was not the case as the submit button was redirecting to the next page even when the validation failed.
Therefore I did some further research and discovered two alternative ways in which I could redirect to another page.

Alternate Redirect Method (1)
The first method I discovered was to use the XMLHttpRequest, thus making use of the power of AJAX technology in order to asynchronously request the server to authenticate the user via the posted variables, return the result and depending on the result, simply decide whether or not to redirect to the next page by using:

window.location.href = "whateverPage.php";

I did not implement this method, but for a detailed explanation of how to use XMLHttpRequest visit OpenJS.

Alternate Redirect Method (2)
The other method I found was to use JavaScript to create hidden a form and fields, which you populate with the user's input and submit programmatically. This method I decided to use, therefore I created a function in my login page which will post three values to the authentication.php page and I have attached my code below:

    
function redirect(){
   try{
     var form = document.createElement("form");
     form.setAttribute("method", "post");
     form.setAttribute("action", "authentication.php");
                        
     //set userID parameter using hidden field
     var hiddenField1 = document.createElement("input");
     hiddenField1.setAttribute("type", "hidden");
     hiddenField1.setAttribute("name", "userID");
     hiddenField1.setAttribute("value", document.loginForm.userID.value);

     form.appendChild(hiddenField1);
                        
     //set password parameter using hidden field
     var hiddenField2 = document.createElement("input");
     hiddenField2.setAttribute("type", "hidden");
     hiddenField2.setAttribute("name", "password");
     hiddenField2.setAttribute("value", document.loginForm.password.value);
                    
     form.appendChild(hiddenField2);
                    
     //set remember me parameter using hidden field
     var hiddenField3 = document.createElement("input");
     hiddenField3.setAttribute("type", "hidden");
     hiddenField3.setAttribute("name", "rememberMe");
     hiddenField3.setAttribute("value", document.loginForm.rememberMe.checked);

     form.appendChild(hiddenField3);

     form.submit();
   }catch(err){
     alert(err);
   }
}


Code Breakdown:
The code on line 3 to 5 creates a form and set its 'action' and 'method' attributes, obviously I want my method to be POST and the action must contain the relative path to the authentication.php file.



                  var form = document.createElement("form");
                     form.setAttribute("method", "post");
                     form.setAttribute("action", "authentication.php");



Next I create an input element, set its type to hidden, give it the desired name and retrieve the user input from the visible fields via the DOM element and attach it to the form element I have just created:

    //set userID parameter using hidden field
     var hiddenField1 = document.createElement("input");
     hiddenField1.setAttribute("type", "hidden");
     hiddenField1.setAttribute("name", "userID");
     hiddenField1.setAttribute("value", document.loginForm.userID.value);


     form.appendChild(hiddenField1);


I repeat this process for every value I want to post and finally I call the form element's 'submit()' function:


form.submit();

This way I can call this function if and only if the validation process is a success, otherwise the request for the authentication.php or any other page for that matter will not be made.

Paper Toss Game Progress
With this posting through JavaScript issue out of the way, I can now focus on implementing the notifications, scoring and sign up function for new users. Now I basically have all I need to carry these tasks out, which are; a good method of posting variables along with my page requests and a solid way of communicating with the MySQL database, which I wrote about in my previous post.
The only visible improvement I did to the game was to change the paper and bin imaged to PNG files so that I got rid of the ugly white boxes around them.
Re-touched paper and bin images to remove white background

12 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 3

In my last post on this coursework I wrote about the flop I ended up doing by using XML instead of a database and concluded by stating I was going back to the drawing board use a database instead...well guess what? It ready!!!
So today I will post on how to connect and communicate with a MySQL database using PHP.

Using MySQL to store data
The first thing you want to do is download and install a MySQL database on the hosting server. I have already installed a MySQL instance when I installed XAMPP which I posted about a while back, so I will move on to the table I needed to store the user's data.

The users table fields and data types
As you might have noticed I did not include a user's position field as now I can use an SQL query to sort the user's out by their score. But I also added the 'DATE_JOINED' field, as I am planning to use this field in cases where more than one user has the same score. This will act as a second ordering field and sort those users according to the date and time they first signed up, which is automatically populated by the database as I've set the default value to a MySQL system variable, named 'CURRENT_TIMESTAMP'.

Connecting to a MySQL database with PHP
To connect to a MySQL database using PHP is very straight forward and can be achieved in a couple of lines, The code below illustrates and displays how it's done.

    $con = mysql_connect("localhost", "root", "MySQLAdmin") or die(mysql_error());
    mysql_select_db("source", $con) or die(mysql_error($con));


Code Breakdown:
The first line uses the 'mysql_connect()' function and passes the MySQL database location, user name and password. This will create the connection with the database and return a reference to that connection which I am storing in '$con'.


The second line is optional, but I decided to do it anyway as what this line does is select which database you wish to use. I named my database 'source' and passed it as a parameter, along with the reference I am storing in memory.


Querying a MySQL database with PHP
Once you have established a connection and want to execute a query, simply use the 'mysql_query()' function and pass the SQL statement as a parameter.
This function can be used not just for SELECT statements but also for UPDATE, INSERT, REPLACE and DELETE as well. The only difference is when you execute a SELECT statement, the resultset is returned, otherwise a boolean value gets returned.
The code snippet below shows how to use this function and how to fetch those results.

    
$result = mysql_query("SELECT USER_FULL_NAME, SCORE FROM USERS", $con)or die(mysql_error());

while($row = mysql_fetch_array($result, MYSQLI_ASSOC)){
      echo $row['USER_FULL_NAME'];
      echo $row['SCORE']."</br>";
}


Code Breakdown:
On line 3 I am using the 'mysql_fetch_array()' function which will return a row in an associative array. Then I use this array to output the results of my query. The while loop is simply used to loop through all of the rows in my resultset.


Disconnecting from a MySQL database with PHP
To disconnect is another simple matter or using just one line of code and the snippet below shows how it's done.

    
mysql_close($con);


The reference parameter I passed is optional, but this will limit the function to disconnect only that connection if more than one connection are open simultaneously.


Conclusion
So communicating with a MySQL database in PHP is quite easy work, but I didn't want to have to repeat this code every time I needed to run a statement, therefore I created a new PHP file and named it DBConnections.php and created my own functions which make use of the code above but in a more dynamic and reusable way.

    
<?php
function execute($sql) {

    $userConn = getConnect();
    $result = mysql_query($sql, $userConn) or die(mysql_error($userConn));
    
    disconnect($userConn);

    return $result;
}

function getConnect() {
    // Make a MySQL Connection
    $con = mysql_connect("localhost", "root", "MySQLAdmin") or die(mysql_error());
    //Set the schema which contains the table/s required
    mysql_select_db("source", $con) or die(mysql_error($con));

    return $con;
}

function disconnect($con) {
    //close the connection
    mysql_close($con);

    //unset this connection
    unset($con);
}
?>


Now all I have to do is include this PHP file wherever I need it by using the following line:
include 'DBConnections.php';

That's it for this post, please feel free to utilise the above code for your own needs. As for my next post I will cover how I managed to redirect to another location and post information by using only JavaScript.


Paper Toss Game Progress
In this section I will simply illustrate the progress made on the coursework so far.
Login Screen


The first page the user will see (i.e. - the index page) is the user login. From this screen the user can input his/her login details in order to access the game. Once the user clicks on the 'Login' button the inputs are validated via JavaScript and if validation is passed, the values get posted to the authentication page which makes use of the DBConnections.php file I described in the previous section, in order to retrieve the user's record by using the posted login details as criteria in the SQL query.
Also from this screen the user can tick the 'Remember Me' check box. For this I will implement the use of cookie variables in order to remember the user's login details in the future. New users can sign up by clicking on the 'Sign Up' button, this will redirect the user to an appropriate form but I will post on these last two features once I have finished implementing them.
Game Area after user login
Once The user is authenticated, he/she is granted access to the paper toss game which I had described in coursework 1. I have made some changes to this page, most noticeably is the background image, which gives a nicer look to the game (N.B. - I am not the owner of this image, I got it from Visual Photos), then I have added some buttons here on the lower left corner and the five paper balls at the top-right corner in preparation for the functions which I will implement in the following days.


P.S. - I will also change the paper ball and bin images to PNG files and remove their white background in order to get rid of the box around them.

11 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 2

Hello there it's me again posting on the second coursework given to me by my lecture. Today's post will not be as I had planned out. Why? Well...if you remember in my previous post on the subject, I decided to make my game store the user's details such as passwords and high scores in an XML file rather than a Database and, well...I ended up learning it the hard way that XML is not suited for that kind of use, but on the plus side I also learnt how to read and write to and from an XML file by using PHP.
Therefore I am still going to post on how to do these two tasks and then conclude by explaining why PHP is not ideal for this kind of use.


Reading from an XML file using PHP
After I had done some research I learnt that you could use the SimpleXML toolset to read from an XML file via PHP.
    
    $xml = simplexml_load_file("userSource.xml");

    foreach ($xml->xpath('//user') as $user) {
        if ($userID == (string) $user->userID) 
            if ($password == (string) $user->userPW) {
                $_SESSION['userName'] = (string)$user->userName;
                $_SESSION['highScore'] = (int)$user->highScore;
                $_SESSION['lastBeatenBy'] = (string)$user->lastBeatenBy;
                $_SESSION['placing'] = (int)$user->placing;
                $_SESSION['Authenticated'] = "yes";

                return TRUE;
            } else {
                return FALSE;
            }
        }
    }
    return FALSE;


Code breakdown:
First the XML file is loaded into an object which I named '$xml'.
$xml = simplexml_load_file("userSource.xml");

Next a For Each loops through all the users, this is achieved by using Xpath with the XML object to identify the specific nodes you are interested in.
foreach ($xml->xpath('//user') as $user)

Comparisons can also be achieved with the XML object. For instance on every iteration, the code checks if the current User's userID child element value matches the User Id stored in a variable named '$userID'.
if ($userID == (string) $user->userID)

Note that I am parsing the XML value into a string. This may not look like much, but it's very easy to forget and I did have some problems with this at the start as I wasn't parsing the values.

Finally to read the values stored from an XML file and into a PHP session variable requires the same technique as when comparing, but instead you simply assign the value to the session.
$_SESSION['userName'] = (string)$user->userName;

Writing to an XML file
Writing to an XML file is as basic as reading, below I have displayed the code I used to carry out this task.

        
        $xml = simplexml_load_file("userSource.xml");
        
        $user = $xml->addChild("user");
        $user->addChild("userName",$_POST['fullName']);
        $user->addChild("userID",$UserID);
        $user->addChild("userPW",$_POST['password']);
        $user->addChild("highScore","0");
        $user->addChild("placing",$UserCount);
        $user->addChild("lastBeatenBy","");
        
        $xml->asXML("userSource.xml");

Code Breakdown:
The first line is exactly like the reading example in which I load the XML file into an object.


The next step is to add an additional <user> node to the already existing XML file and store it as an object in order to add the required child nodes to it.
$user = $xml->addChild("user");
The parameter passed to the 'addChild()' function represents the name of the node to be created.

To add child nodes with values to the <user> node, which is currently in memory, you use the 'addChild()' function once more, but this time pass the value as an additional parameter.
$user->addChild("userName",$_POST['fullName']);
The value parameter in the above example is being retrieved directly from the  POST variable, although variables and hard coded values can also be used. 

Why XML is not ideal for storing info about users on a web application
So, here is how it all went down. after I hanaged to read and write into the XML file, it dawned upon me...This game will probably have more than one user playing it at the same time!

So if, lets say user `A`, opened the XML file to memory in order to write his/her details to the file and user `B` opened the file as well to save his/her new high score, in the meantime user `A` saved the file with the new details, but the version user `B` has opened doesn't have the information entered by user `A`, therefore once user `B` saves, he/she will overwrite the changes made by user `A`.


To solve this problem you could try to devise some kind of collision detection system, but unless you are forced to use only XML, that is not a feasible solution, therefore I will have to go back to the drawing board and make my game store its data on a database.




"Mistakes are a part of being human. Appreciate your mistakes for what they are: precious life lessons that can only be learned the hard way. Unless it's a fatal mistake, which, at least, others can learn from." - Al Franken

9 May 2012

CMT3313 - Week 10 Post - Mobile Technology

Introduction


This week's blog will focus on the ever changing mobile technology world, and when I say ever changing, I mean it! As by the time you read this post, it would probably already be obsolete :( 


Apple vs Android
So, what do I mean by mobile technology world? Obviously it's everything that has to do with mobile devices such as phones, tablets, even watches.
If you look at the hardware aspect at a glance it's obvious the the leading players are currently Apple, Samsung, HTC, RIM and Nokia. But in this post I will focus more on the software aspect, which instantly gives us:

  • iOS
  • Android
  • Blackberry OS
  • Symbian OS
  • Windows Phone
Currently the strongest players are Apple's iOS and Android, the open source giant, therefore I will continue this post by concentrating on these two.

StatCounter's European Statistics of top mobile operating system from April 2011 to April 2012 
Mobile Development
To start developing a mobile application you must first decide on what platform you want your application to run on as Android use mostly Java to code their applications while Apple prefer the Objective C language.
In this section I will explain the basics of what you need to know to start off on both platforms.

Apple iOS
Developers must register with the Apple iOS Developer Program and pay the annual fee of €77. This will give them access to an array of tools, tips, debug tests and guidelines.
Keep in mind that to launch your application on the iOS market, your application must pass approval, thus adhere to strict regulations on what you can and cannot do.

Android
To start off with Android it's a little less difficult, as being an open source project, android provides it's starter kit for free. This kit consists of the Android Software Development Kit (SDK), sample projects, source code, development tools and a testing emulator. Also, Android provides loads of how-to videos, technical articles and step-by-step instructions on application development.
The only costs are a one-time fee of just €19 when you decide to launch your application into the play store. Which by the way doesn't require strict approval (although this is not always a good thing).

Other development tools
Smartphone applications have become sort of a trend nowadays and everybody wants to have their own mobile application or mobile website for multiple reasons, therefore many third-party tools are also available, such as Appcelerator, PhoneGap and MobDis. These tools are designed for web developers or people who aren't professional developers to create mobile content without having to learn Objective C or Java.

Conclusion
To wrap up this post I would like to mention that rumours are going around saying that Facebook is working with HTC to jump on the wagon by producing a smartphone which will run a heavily modified Android platform and incorporate all of it's services and features with easy access.
To read more about this subject visit Forbes.

CMT3313 - Week 9 Post - PHP Session & PHP Cookies

Hello there, I assume you must have noticed I skipped week 8's post, this is because we covered PHP & SQL connections during our lecture. Coincidently I had already covered this subject on my own and posted about it in week 7's post, where I gave an example of how to query data from a MySQL database and display the results in a generated HTML table. 


This week though, we covered using Session variables and Cookies with PHP, so this post will cover these subjects in the following way:

  • PHP Session
  • PHP Cookies
PHP Session

First off, let me start with a short note on what a Session is in general.
A session is used to store information on a single user on the server. Once a session is set, it will be available for use on every page of the hosted web application.
Sessions actually work by assigning a unique ID (UID) to every user. This UID can either be stored in a cookie file or passed along with the URL. This way the web server can keep track of who the user is, therefore overcoming the problem introduced by the fact that HTTP is stateless, as I had previously discussed in a previous post where I covered an introduction to cookies.
The important thing to remember about Session variables is that they have to be deleted once the user leaves the web site, as although these take little space individually, a hosted application receiving a lot of hits from different users every day would easily generate a lot of session variables, thus negatively effecting the performance of the hosting server.

Starting a Session with PHP
Before you could declare a session variable in PHP, you must first start the session by calling the 'session_start()' function. This will register the user's session on the server, assign a UID for that user's session and allow you to start saving user information.

N.B - It is important to call this function at the start, before the <HTML> tag.

<? PHP session_start(); ?>
<HTML>
.
.
.
</HTML>

Storing a Session variable with PHP
To store a session variable you must use the superglobal variable '$_SESSION' and define the name of the session variable you want to declare within  square brackets and inverted commas like so:

<?php
   $_SESSION['userName'] = 'John';
?>

The example above will store will store the value: 'John' in the session variable named 'userName'. To output the value of this session variable on the browser screen we use the function 'echo()'

<?php
   echo $_SESSION['userName'];
?>

Removing a Session
To remove session variables there are two methods, either remove a specific session variable or remove all the registered variables all at once.
To remove a specific session variable you must use the 'unset()' function an pass the session variable you want to remove as a parameter like so:

<?php
   unset($_SESSION['userName']);
?>

If on the other hand, you have more than one registered session variables and you want to remove them all at once, you simply use the 'session_destroy()' function.

<?php
   session_destroy();
?>

PHP Cookies
Cookies with PHP
A cookie is a small file which the server embeds on the user's machine. Then the next time the user visits the website, this file is sent along with the request towards the server.
This action is normally used to identify users which have already visited the website before, therefore, unlike a session, a cookie is not temporary.
But what use can this have you might ask? Well for instance, take Google Plus, you only login your account details the first time, then when you visit the site a second time from the same machine (while taking it into consideration that cookies are enabled) the site automatically knows who you are, logs you in immanently and provides you with links to all your Google applications, such as Gmail, Blogger, Docs, Calendar, etc..


Create a cookie using PHP
A quick note before explaining how to create a cookie, I would like to point out that you can set a cookie to expire within a stipulated amount of time.
So, to create a cookie in PHP you must use the function 'setcookie()' before the <HTML> tag of a PHP page like so:


<?php setcookie('user', 'John', time()+3600); ?>
<HTML>
.
.
.
</HTML>


The example above creates a cookie named 'user', stores the value: 'John' and sets it to expire in 1 hour.


N.B. - The third parameter represents the expiry time in seconds. Therefore if you want the parameter to expire in 5 days, simply calculate how many seconds 5 days amount to and pass that value in the parameter.


Retrieve a cookie using PHP
To retrieve a cookie you must use the superglobal variable named, '$_COOKIE' and define the cookie's name in square brackets and inverted commas. But to be safe, it is good practice to check if that cookie exists before trying to read it's value.
This is achieved by using a PHP function which I used in my last post regarding coursework 2 and that is the 'isset()' function. Basically this function receives a parameter and returns a boolean value, stating whether or not the received parameter exists or not.


<?php 
    if(isset($_COOKIE['user'])){
        echo "Welcome back ".$_COOKIE['user'];
    }
?>


Deleting a cookie using PHP
To do this, there isn't a specific function dedicated to do this job, instead you use the previously mentioned 'setcookie()' function and set an expiry parameter which has already passed, for example:


<?php
   //sets the expiry to 1 hour ago 
   setcookie('user', '', time()-3600);
?>


Conclusion
So, which are the best, Cookies or Sessions?
The answer is NONE, you should not use one technology instead of the other, but mesh the use of the two together to get the best of both worlds.
What I mean by this is you could store the user's name and encrypted password in a cookie to enable auto-login and use session variables to store information on the user's temporary item basket.