More About CA272 Final Project


Since I mentioned the CA272 final project a little in the last post, I think it’s best to talk more about this topic.

I took CA272 class in the Spring of 2009. It is known as Professional Website Development. Actually to me, this is not a professional class. Instead, it is a very basic class: it doesn’t include sever-side script languages nor JavaScript, just basic HTML4. At that time however, I didn’t know jQuery and PHP until the very end of the semester.

As you can see through the source code of the Final Project page, all of the AJAX and JavaScript functions were created by myself. Because I discovered jQuery during the last week of final project submission, I hurriedly added some animated transitions to the pages using jQuery without the deep understanding of jQuery. Therefore, the animation looks a little incomplete.

The presentation below explains the most of features on the site:

Note that because I don’t have my own website at the time, I copied all the final project files to a free hosting. Therefore, the URL at the end of the video is not valid anymore, use http://robbychen.com/ca272/final/ instead.

My Almost Completed Second WordPress Theme

I have been making this second Worldpress theme for the final project in my CMS class. Compare to the first theme I made, it has more customized features such as custom background and custom navigation menu, the design of the theme is more complex, and the theme layout becomes more standard. Here is an overview of its features copied from this page:

  • Custom background
  • Custom menu (only allow one level of drop-down menu)
  • Three widget areas
    • Left widget area – default widget is categories if no widget is set
    • Right widget area – default is the search form
    • Bottom widget area – default is tag cloud
  • Show category and tag list at the end of each post, display a message  if there is no category / tag assigned
  • Custom 404 page
  • Display 10 recent posts under each post

For more information on each of the above features, and to see the code snippets for them, read the original post.

This theme is still incomplete because I need to add the comments area on the post page, as well as some design changes. The deadline for this final project is next Thursday, July 22. I still have some time to finish up.

I will post the final progress of the theme and its source code when it’s completed.

Calculate the degrees from the given Data to draw PHP Graph

During the final exam for my PHP class today, I encountered a math problem that I learned long time ago. The problem is to draw a chart based on the data from the database in order to show the ratio between men and women on a pie chart. The number of men represented as blue and red represent as women. I thought that it was as simple as draw two arcs using imagefilledarc function. However, when I noticed that the data needs to be in degrees in order to use this function. I totally forget how to convert a number to a degree since I haven’t been practice math for two years. Thanks to Google, I learned how to do the conversion on Yahoo Answers. The formula that I came up with is the degree of each men and women equals the number of men or women divide by total number of men and women multiply by 360. Therefore I wrote the following code:

<?php

$image = imagecreatetruecolor(300, 300);

$blue = imagecolorallocate($image, 0, 0, 255);

$red = imagecolorallocate($image, 255, 0, 0);

$white = imagecolorallocate($image, 255, 255, 255);

imagefill($image, 0, 0, $white);

$male = $_GET['m'];

$female = $_GET['f'];

$total = $male + $female;

$maleDegree = $male / $total * 360;

$femaleDegree = $female / $total * 360;

imagefilledarc($image, 130, 130, 200, 200, $femaleDegree-270, $maleDegree-90, $blue, IMG_ARC_EDGED);

imagefilledarc($image, 120, 130, 190, 190, $maleDegree-90, $femaleDegree-270, $red, IMG_ARC_EDGED);

imagepng($image);

imagedestroy($image);

?>

The f and m variables are URL variables, which means I can pass the number of males and females inside the normal img tag:

<img src="3_image.php?m=<?php echo $numMale; ?>&f=<?php echo $numFemale; ?>" alt="Problem 3 - Graph" />

You can download the source code here to experiment with it. There is a MySQL database file inside the downloaded archive, which it contains the needed MEMBERS table for this script.

Path Navigation using PHP and ColdFusion

This morning I wrote a script for both PHP and ColdFusion that dynamically generate a navigation bar like the one in the Nautilus GNOME File Browser:

It uses URL values to generate content for the navigation bar. Basically, it convents the URL string to an array based on the “/” or “&,=” pattern. It then forms navigation bar like style by using converted array inside a loop. This technique is actually inspired by the professor in my PHP class. I came up with this idea when she talks about how to use one PHP page to translate to several languages based on the URL. The following code is based on this URL style: http:www.example.com/?var=value&number=94

Here is ColdFusion code:

<cfoutput>

<!—- Change it to CGI.SCRIPT_NAME for use with URL path —>
<cfset variables.urlQuery=CGI.QUERY_STRING>

<!— Use listToArray() to convert CGI variable to an array
Change & to / for use with URL path —>
<cfset variables.arrayQuery=listToArray(“#variables.urlQuery#”,’&’)>

<!— Use arraylen() to determine the size of the array —>
<cfif arraylen(variables.arrayQuery) NEQ 0>

<!— &gt; is the greater than symbol —>
<a href=”/Students/Students/0111″ title=”Home”>Home</a> &gt;

<cfloop from=”1″ to=”#arraylen(variables.arrayQuery)#” index=”i”>

<!— Doesn’t need this statement if used with URL path —>
<cfset variables.splitQuery=listtoArray(“#variables.arrayQuery[i]#”,”=”)>

<!— Doesn’t need this loop if used with URL path —>
<cfloop from=”2″ to=”#arraylen(variables.splitQuery)#” index=”o”>

<cfif variables.arrayQuery[i] CONTAINS “projectid”>
Projects &gt;
<a href=”?projectid=#variables.splitQuery[o]#”>Project #variables.splitQuery[o]#</a>
</cfif>
</cfloop>
</cfloop>
</cfif>
</cfoutput>

The following is PHP code. The URL path method mentioned in the above code also works in the code below:

<?php
if (!empty($query)) {
$query = $_SERVER[‘QUERY_STRING’];
$queryArray = explode(“&”,$query);$_SERVER[‘QUERY_STRING’] ?>
<a href=”
<?php if ($_SERVER[‘SERVER_NAME’]==’localhost’) { ?>
/ca282
<?php } else { ?>
/Chen
<?php } ?>
“>Home</a> &gt;

<?php
for ($i=0;$i<sizeof($queryArray);$i++) {
$splitArray = explode(“=”,$queryArray[$i]);
for ($o=0;$o<sizeof($splitArray);$o++) {
$firstLevel = $splitArray[$o];
$secondLevel = $splitArray[++$o];
switch ($firstLevel) {
case ‘project': echo “<a href=”?page=projects”>Projects</a>”;
break;
case ‘page':    echo ”;
}
if ($firstLevel == ‘project’) {
echo ‘ &gt; <a href=”?project=’. $secondLevel . ‘”>Project ‘. $secondLevel . ‘</a>';
}
if ($firstLevel == ‘page’) {
switch ($secondLevel) {
case ‘about': echo ‘<a href=”?page=about”>About Me</a>';
break;
case ‘projects': echo ‘<a href=”?page=projects”>Projects</a>';
}
}
}
}
}
?>

Google Maps API and ColdFusion

While I was experimenting with Google API for my CA 288 ColdFusion class final project, I discovered that the ColdFusion variables can be used within the script tag. So I tried it out. I put the cfoutput tag outside the script tag in order to use the ColdFusion variables inside the script tag. And then I added cfif statement inside script tag to set the default latitude and longitude values to New York if there is no URL variables. Here is the cfelse part of the code:

var co_lat=#URL.a#;
var co_long=#URL.o#;
initialLocation = new google.maps.LatLng(co_lat,co_long);
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});
contentString = "&lt;br /&gt;#URL.d#:" + "&lt;br /&gt;" + "Latitude: " + co_lat + "&lt;br /&gt;" + "Longitude: " + co_long;
map.setCenter(initialLocation);
infowindow.setContent(contentString);
infowindow.setPosition(initialLocation);
infowindow.open(map);

I also used ColdFusion variables to convert them into the JavaScript variables as you can see on the first two lines of code. I also added a marker to the map to show the accurate location for the data provided. This is best used for creating maps from a list of places. For usage example, go to http://160.253.0.40/Students/Students/0111/browserGeo.cfm?d=Addo%20Entrance&a=-33.44431&o=25.73872. To download the source code, visit http://code.google.com/p/ca288-final-spring-2010-mc/downloads/list

PHP

PHP Form Validation Tip

While doing the assignment for my CA 282 (http://zebra0.com/Chen/?project=3) PHP class today, I came up with a trick to minimize the amount of code that I need to write for the validation rule of each form element. This trick especially best used for validating forms with lots of form fields. The following is the PHP code:

if (isset($_GET['submitted'])) {
  $field="username,password,pwconfirm,fname,lname,address,city,state,zip,email";
  $fieldName="User Name,Password,Confirm Password,First Name,Last Name,Home Address,City,State,Zip,Email";
  $field = split(",",$field);
  $fieldNm=split(",",$fieldName);
  for ($i=0;$i<10;$i++) {
    if (empty($_POST[$field[$i]])) {
      $errorMsg .= $fieldNm[$i]." is required.<br />";
      $success .= "False";
    }
    else {
      $success .= "True";
    }
  }
  if (!strstr($success,"False")) {
    $errorMsg="The form successfully submitted.";
  }
}
else {
  $errorMsg = "";
}
echo "<div id="noVal">".$errorMsg."</div>";

As you can see from the code above, I use split function to convert the combined form field names and the actual name for each form field to arrays. I then used a for loop to loop between form fields to validate the form. This is a simple form. It only checks all the form fields that left blank. You can use continue command inside the for loop for certain form fields that don’t need to be validated. You can also use email validation and password=password_confirm validation inside the for loop. Also note that the noVal id at the end of above code is just used to display the error massages to red color and bold.

The ColdFusion website is now fully data-driven

I learned a way to write code for the menus by using database instead of using cfswich. Now the course website is completely database-driven. I used the CMS approach to redesign the links in each menu. Here is the entire code for the content page that corresponce to the menu items:

<cfquery name=”qGetURL” datasource=”DSN0111″>
SELECT *
FROM tblMenu
WHERE 0=0 AND
<cfif isDefined(“URL.projectid”)>
menuID = #URL.projectid#;
<cfelseif isDefined(“URL.pageid”)>
menuID = #URL.pageid#;
<cfelse>
menuID = 18;
</cfif>
</cfquery>

<cfoutput>
<cfset filePath = ExpandPath(“#qGetURL.linkLoc#”)>
<cfif fileExists(filePath)>
<cfinclude template=”../#qGetURL.linkLoc#”>
<cfelse>
<div id=”noVal”>Not Found</div>
<cfinclude template=”index.cfm”>
</cfif>
</cfoutput>

As you can see from the above code, the file location and the file names are stored in the database instead of the page content. This way, I can create web pages inside site directories and then include it to the website through database without change the above code.

I also plan to create a ColdFusion web application that can directly update the database without launch MS Access. Right now I’m using CFEclipse to write the ColdFusion code on my Fedora system and virtualized Windows XP through VirtualBox to modify and viewing the database. My goal for this web application is to allow me to modify or view the database with less or no MS Access usage.

For those who don’t know, my ColdFusion course is Microsoft Access based, not MySQL based. I successfully installed ColdFusion 9 on my Fedora system, but I failed to install MS Access driver onto the system. That’s why I plan to create this application in the next few weeks.

Learning PHP Object Oriented Programming

Today I have learned about using Object Oriented Programming (or OOP) in PHP. It is very easy once you understand the structure of the OOP and have lots of practice on this technique. I learned this while I was looking over my Google Reader before my PHP class. I’m taking beginning PHP course this semester. This means that the OOP topic is not included in this course. You need to know basic PHP structures like functions and loops in order to understand OOP. Fortunately, I already self-learned PHP language during the end of year in 2009 through Lynda,com. So I tried to use OOP in the PHP script. At first. I think that I will practice more of this technique because this is new to me. I followed the simple tutorial on this website. After finishing the tutorial, I went to attend the PHP class. To me surprise, it had a test today. I happened to need more practice over the OOP. I took the second part of the test which was the hands-on test entirely using OOP. Here (http://zebra0.com/Chen/exam1.php) is the Object-oriented based test page. The following is one of the classes I created:

class todayDate {
  public $month;
  public $mesg;
  public function __construct($tdMon) {
    date_default_timezone_set("America/New_York");
    $tdDate = date($tdMon);
    $this->month=$tdDate;
    switch ($tdDate) {
      case "June":
      case "July":
      case "August":
        $this->mesg="Drive safely: school is in session";
      break;
      default: $this->mesg="Enjoy your vacation: Drive safely";
    }
  }
  public function getMonth() {
    return $this->month;
  }
  public function displayMsg() {
    return $this->mesg;
  }
}

I just learned the basics of Object Oriented Programming so I can only write these basic classes. As I learn more about OOP, I will improve my code for better readability and performance.

For more information and to learn more about Object Oriented Programming in PHP, visit this article on devarticles.com.

Successfully using ColdFusion array for the First Time Without Knowing Anything

I just improved my ColdFusion class website (http://160.253.0.40/Students/Students/0111/). I used more fileExists functions to automate the detection of the project files in the URL variables. Now I don’t have to worry about adding the projects to the cfswitch statement anymore. Here is the code snippet for one of my cfcase statements:

<cfcase value=”4″>
<cfif fileExists(filePath[4])>
<cfinclude template=”../projects/project4.cfm” />
<cfelse>
<div id=”noVal”>This project is not available yet!</div>
<cfinclude template=”index.cfm” />
</cfif>
</cfcase>

Noted that I used an array in the fileExists function. Here is the cfloop statement for the filePath array:

<cfloop from=”1″ to=”10″ index=”i”>
<cfset filePath[#i#] = ExpandPath(“projects/project#i#.cfm”)>
</cfloop>

As you can see, I used an array inside cfset statement to store 10 ExpandPath functions. This is my first time to use the array in a ColdFusion variable. In fact, I didn’t know anything about how to use ColdFusion array. I just applied the array based on the other programming languages that I have already known. According to course syllabus, we should learn ColdFusion array at later chapter.

At first, I used filePath#i# inside the loop to declare a regular ColdFusion variable. ColdFusion outputted an error stated that “ColdFusion was looking at the following text: #” . Then I tried the traditional method of adding an array by surrounding the loop variable with a pair of brackets. I was very surprised that it actually worked.

I applied the same technique to the title of each webpage so that I no longer forget about adding project title to the title.cfm when completed a project. Here is the code snippet for one of the cfcase statements:

<cfcase value=”7″><cfif fileExists(filePath[7])>#titleName[7]#<cfelse>#defaultTitle#</cfif></cfcase>

The defaultTitle variable is the default title on the site homepage.

The following are the additional updates for the site:

  • Projects are now re-organized
  • Project 1 has become homepage
  • Project 2 has changed to project 1
  • New project 2, Advanced SQL, was completed and added to the homepage