0

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.

0

Use Array to Populate the form with PHP

When I was doing my practice final for the PHP class today, I came across several problems for easier way to populate the form, especially with check box and option form controls. These two controls need to be repeated each time when new items were added to the list. Of course I could copy and paste the previous statement and edit it accordingly, but I want to make it easier by just input the new items into the appropriate arrays. Here is what I did to the multiple selection control:

<select multiple size="5" name="skills[]" id="Skills">
    <?php
        $selected = new prefilll();
        $webprogramming = array("AJAX","ColdFusion","HTML 5","JavaScript","JSP","PHP");
        $computerprogramming = array("Basic","C/C++","Java","Linux");
        $skillset = array("Web Programming"=>$webprogramming,"Computer Programming"=>$computerprogramming);
        foreach($skillset as $skillNum=>$skillsets) {
            echo "<optgroup label="$skillNum">n";
            foreach($skillsets as $programmingSkill) {
                echo "<option";
                echo $selected->selected("skills",$programmingSkill);
                echo " value="$programmingSkill">{$programmingSkill}</option>n";
            }
            echo "</optgroup>n";
        }
    ?>
</select>

And here is the check box control:

<?php
     $counter = 0;
     $checked = new prefilll();
     $jobtypes = array("full"=>"Full Time","part"=>"Part Time","weekdays"=>"Weekdays","weekends"=>"Weekends");
     foreach($jobtypes as $labelFor=>$values) {
         $counter++;
         echo "<input type='checkbox' name='jobtypes[]' value='{$values}' id='{$labelFor}'" . $checked->checked("jobtypes", $values) . " />n";
         echo "<label for='{$labelFor}'>{$values}</label>n";
         if ($counter == sizeof($jobtypes) / 2) {
             echo "<br />n";
         }
     }
?>

Note that I used a class in the above code segments, prefill. This class is used to reselect the items in the check box and option controls if there is a validation error.

Following is the code for the prefill class:

class prefilll{
    function selected($items,$Item) {
        if (isset($_POST[$items])) {
            $items = $_POST[$items];
            if (in_array($Item, $items)) {
                    $Selected = " selected";
                }
            else {
                $Selected = "";
            }
        }
        else {
            $Selected = "";
        }
        return $Selected;
    }
 function checked($items,$Item) {
        if (isset($_POST[$items])) {
            $items = $_POST[$items];
            if (in_array($Item, $items)) {
                    $checked = " checked";
                }
            else {
                $checked = "";
            }
        }
        else {
            $checked = "";
        }
        return $checked;
    }
}

You can download the above source code from here along with the whole source file if you want to experiment with it yourself.

0

Playing Around with PHP URL Extraction

I discovered today that there is a feature in PHP that can grab current URL through $_SERVER['REQUEST_URI'] and convert it into an array using explode function. I think this is extremely useful to me. Partly because I always wanted to have an URL that is similar to the URL for this blog. Another reason is that I don’t have to edit my sever configuration either directly or through PHP to achieve the same result. The method I use to create an URL that only contains the folder of the page, that is, the page is index.php, might be useful for small websites that have less than fifty web pages or possibly less. I didn’t test it on a large set of web pages because I just thought about using this type of URL format in the final project for my CA 282 class. It is a four-page project, therefore I cannot guarantee that it can work on a larger set of web pages. I personally think that it can become disorganized and confused once I have a little more web pages by using this method. Here is the code if you want to test it. Basically, it includes all the files inside the main index page based on the value at the last slash of URL, e.x. http://www.example.com/folder/item :

    $currentURL = $_SERVER['REQUEST_URI'];
    $URLpart = explode("/", $currentURL);

    $endURL = $URLpart[sizeof($URLpart)-2];
        switch ($endURL) {
            case 'signup':    //  http://zebra0.com/Chen/final/account/signup/
                include_once 'includes/signup.php';
                break;
            case 'login':     // http://zebra0.com/Chen/final/account/login/
                include_once 'includes/login.php';
                break;
            case 'account':   // http://zebra0.com/Chen/final/account/
                include_once 'includes/account.php';
                break;
            case 'signout':   // http://zebra0.com/Chen/final/account/signout/
                include_once 'includes/signout.php';
                break;
            default:
                include_once 'includes/index.php';
        }

And the index.php file inside each of the folder simply include the main index.php at the root of the project folder. Because of the nature of the included file, I used the dynamic path using PHP $_SERVER array to generate an absolute URL for the links and style sheets instead of the static ones.

$currentURL = $_SERVER['REQUEST_URI'];
$URLpart = explode(“/”, $currentURL);

$endURL = $URLpart[sizeof($URLpart)-2];
switch ($endURL) {
case ‘signup’:
include_once ‘includes/signup.php’;
break;
case ‘login’:
include_once ‘includes/login.php’;
break;
case ‘account’:
include_once ‘includes/account.php’;
break;
case ‘signout’:
include_once ‘includes/signout.php’;
break;
default:
include_once ‘includes/index.php’;
}

0

PHP Form Validation Tip

While doing the assignment for my CA 282 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.

0

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 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.