PHP Diary | PHP Housekeeping | PHP Scripts | TD Scripts.com

[back]WB01624_.gif (281 bytes) 12/24/99 "Mathematical Averages In PHP & Bug Fix" WB01626_.gif (272 bytes)[next]

Getting averages in PHP

Now that we have a database of ratings for each day (well assuming you are rating each diary entry that is) we can open and read that database and dynamically display results. First we need to know how to get an average. To do that we need two pieces of data: the accumulated total of all ratings and the total number of votes. Let's look at the PHP code to get an average:

<?
$total_ratings = (3+2+3+1+5+2+3);
$total_votes = 7;
$average = $total_ratings / $total_votes;
print("The Average Rating Is: $average");
?>

Example #10: Getting an average number using PHP

Bug Reports!

One astute reader who is following this diary has pointed out a bug with my voting script as is and posed a question about cookies. By the way, if you ever see any bugs with my code please submit your feedback to webmaster@php-scripts.com and if relevant I will address in my next diary. Remember, that I am learning too :)  You can also submit suggested bug fixes to my code examples and I will give you credit. Since I get anywhere from 300-400 emails a day I can't personally respond to each, but I do read every email and if I find a particular relevant one I will be happy to include in my diaries:

"...I've been following your php pages. Very cool. thanks.
but i'm a bit confussed about cookies.  can you just refenece a cookie like any other variable?

Cookies are stored in the HTTP_COOKIE_VARS array based on the name you used when setting the cookie. In my example I used test (see rate code from 12/23/99) as the variable name, so when I want to check for the existance of the cookie I would simply do an if(isset($test)) to see if the variable test exists. If it does, the return would be true and I would know the cookie existed and would not need to set one. I could of course examine the value of the set cookie by doing if($test == "string or value here"). Remember that quotes are only necessary for strings. However, if the cookie did not exist, I would need to set one.

...also i found a bug with your voting page.
if you vote on one page and then on another you can go back and vote on the first."
                                "ifo"- email witheld

The reason why this was happening was because my script was only checking one value against the cookie, if the cookie existed with a different value it was acting as if the cookie never existed, which was a bug. Every time a new rating is registered from the same person it removes the cookie that was placed from another page. There are several ways to fix this bug. One involves putting the cookies into an array. The code for doing this is below:

<?
$security_domain = "www.php-scripts.com";
$security_domain2= "php-scripts.com";
$url = explode("/", $HTTP_REFERER);
if(ereg("$security_domain|$security_domain2", $url[2]))
{
  $filesplit = explode(".", $url[4]);
  $filename = $filesplit[0];
    if(ereg("[0-9]{6}", $filename))
    {
      $check = "rated";
      $check .= $filename;
        if (isset($rated))
        {
         // the person has rated another page so do not overwrite cookie
         // add routine to make an array with all cookie values
         $count = count($rated);
         $i = 0;
           while($i < $count)
           {
             if($rated[$i] == $check)
              {
               print("<HTML><BODY>You have already voted. Thank you.</BODY></HTML>");
               exit;
              }
            $i++;
           }
        // since no rate on this page yet, add new rating to array
        $rated[] = $check;
        $count++;
        $i=0;
          while($i < $count)
         {
          setcookie("rated[$i]", $rated[$i], time()+86400);
          $i++;
         }
        $filename .= ".dat";
        $newrate = fopen($filename, "a");
        if ($newrate)
        {
         fputs($newrate, "$rating\n");
         fclose($newrate);
         print("<p>Thanks for rating my page: $HTTP_REFERER ");
         print("<br>with a rating of: $rating</BODY></HTML>");
         exit;
        }
    }
    else
   {
   // no cookies exist so set initial cookie and write file
   setcookie("rated[0]", $check, time()+86400);
   // time to open the unique file for appending new rating
   $filename .= ".dat";
   $newrate = fopen($filename, "a");
     if ($newrate)
     {
      fputs($newrate, "$rating\n");
      fclose($newrate);
      print("<p>Thanks for rating my page: $HTTP_REFERER ");
      print("<br>with a rating of: $rating</BODY></HTML>");
     }
   }
}
else
{
  // diary page is not valid

  print("<HTML><BODY><p><strong>Sorry this is not a valid diary");
  print("page</strong></BODY></HTML>");
  }
}
else
{
// link did not come from domain, security violation
print("<HTML><BODY><p><strong>Sorry, you cannot run this");
print(" script from this location</strong></BODY></HTML>");
}
?>

You might notice the repetition of the file appending routine and this can (and will) be changed in a future lesson when we get more into the use and appropriate use of functions. Suffice to say that code which repeats itself is often better put into a function, but I wanted to show you here how it worked in a logical order. I added comments // which I am not sure we have discussed up to this point. Anything you place after // is ignored by PHP and it is very useful to comment your code so that fixing something later can be easier. Below you will find that you are no longer able to vote twice by going back and forth between days. The bug has been fixed.   Another note on the code above that you may think was needless repetition. The $i=0 is in there twice.  Why? Well if I don't reset $i to 0 on the second while loop it will never be executed because $i would already equal the value of the array. The bug is gone :)

Hosts that support PHP search engine

There is a cool search engine on the official PHP site that has hosts which support PHP that I just discovered while surfing today. You can search by version, by location of host and more! I will still probably do my own little listing of hosts that I know people are using php successfully, down the road, but if you are looking for a host right away, check this search engine out.

PHP Knowledge Base

Looking for knowledge? Check the PHP Knowledge Base (http://www.e-gineer.com/phpkb/). It is also searchable and contains plenty of useful information on PHP.

Have a safe and Merry Christmas 1999, this diary will probably not be updated again until Sunday, December 26, 1999.

How useful did you find this diary entry? Avg Surfer Rating: 305603257501991350000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.00 (325)

[back]WB01624_.gif (281 bytes) 12/24/99 "Mathematical Averages In PHP & Bug Fix" WB01626_.gif (272 bytes)[next]

PHP Diary | PHP Housekeeping | PHP Scripts | TD Scripts.com

Copyright 2000 php-scripts.com Last Modified 01/6/00 05:46