PHP Diary | scriptschool.com | PHP Scripts | TD Scripts.com

Guts or Glory Poker PHP - A casino-style card game written entirely in PHP


[back]go back 07/30/00 "Functions, globals, mySQL, brief object oriented programming" go forward[next]

The most useful reader-rated php-scripts.com diary entries updated daily

Now that we have dozens of diary entries, I'd like to display the most useful diary entries so that people who don't want to visit chronologically can visit the diary entries other readers have found the most useful. We already have done most of the work before in prior entries by creating the average function which will total each diary page and come up with an average on a page by page basis (see the bottom of the page). Since it could be somewhat server intensive to dynamically open and close all these files (if you want to know more about how opening dozens of files dynamically can be a disadvantage (especially if the information inside these files isn't frequently changing), then read the diary entry on 010700 for a further discussion), I'm going to make this part of the search log function we created before so that when we build the list of search pages with meta tags, we can also recalculate the average, but it will be a standalone script that can function on its own. We will require it into the search log script described on 010700. Yes, we could do this dynamically but again, I usually try to program with the path of least server resources used, that way as your site grows and you get more traffic, your scripts will not need severe modification to continue functioning as in intended. As you can probably see, we are building sort of a "daily update" script that could be executed once a day or multiple times per day (even as often as hourly would be fine). It is useful to plan your website building like this. If you do things today with the idea that you will one day have thousands of pages, it will make your life a lot easier modifying those pages.

The first step - get the next filename

We need to review the routine for how to cycle through a bunch of files in a directory. We can use an object dir or use the opendir function. I'm going to use the object method this time, since we used the opendir in our former version. It is kind of like using print and echo in the sense that each will do the same thing. Working with objects of course is an entirely different concept and one that can be complex for those newer to object-oriented programming, so let's review the code to cycle through our directory and pull out the .dat files, and an admittedly brief review of object-oriented programming:

$datapath = "/home/usr/www/votedir/data";
chdir("$datapath");
$maindir = dir(".");
$maindir ->rewind();
while($thefile=$maindir->read()) {
   if(($thefile != ".") AND ($thefile != "..") AND ($thefile != "index.html")) {
     $myvalue = average2("$datapath/$thefile");
     $myvalue = sprintf("%.2f", $myvalue);
     $file = explode(".", $thefile);
     $phpfile = "http://www.yourdomain.com/votedir/" . $file[0] . ".php3";
     $meta = get_meta_tags($phpfile);
     $desc = $meta["description"];
       // generate the mySQL query
       $query = "INSERT into avg_tally VALUES (0, ";
       $query .= "'$myvalue', '$file[0]', '$desc')";
       mysql_query($query, $mysql_link);
   }
}
$maindir->close();

Line1: sets the absolute path to the vote directory where our .dat files store all the averages.
Line2: changes the active directory to this.
Line3: sets the $maindir to the current directory. A single period means we are using the current directory. In object oriented programming, variables are the properties of an instance.
Line4: makes a reference to an instance to rewind the directory to the beginning. The -> is the symbol used to reference a class method or property.
Line5: starts the loop to cycle through the files in the directory using the read().
Line6: eliminates the "." and ".." as valid filenames by saying "as long as the filenames are NOT (!) "." and ".." AND "index.html" go ahead and proceed. index.html probably exists in this directory if it is a public directory. If you are storing your voting files in a non-public directory you wouldn't need this. As you might know, if you have no index.html file in a directory then people can view the directory tree in a public directory. Any secure files should be stored outside the public directory, but I included here to illustrate how you can combine multiple AND in conditional instead of making separate independent if clauses.
Line 7-8: converts the results of the calling the new function
average2.
Line 9: strips out the .dat that would be redundant if stored in the mySQL database.
Lines 10-12: get the meta tag description for that file from the actual page, this will be useful for a better description of the diary.
Line 13-16: build the mySQL database query to insert the data into the database. I'll show you the SQL syntax for creating the mySQL table on line 13 in a minute, but we could also have loaded this into an array and sorted it using a custom sorting routine. The built-in sort function would not work because sort would sort by ASCII order since the array contained a string, and we want to sort by floating point numbers. We could use the built-in usort function and build our own sorting routine but frankly it is a lot easier and quicker to use mySQL (unless a mySQL database is not available, of course). The use of the new
average2 function may seem complex at first, so we'll get into more about why we need to do this in a minute. We do need to store the filename so that we know what file to link. We will be creating this new function in a minute and passing the path to the file we want to get the average from and storing it in the mySQL database.
Lines 17-19 close the loops and the object directory. Remember, that we could also have written line 10 to read closdir($maindir); This should help illustrate (albeit briefly) using OOP (object oriented programming). Here is the SQL syntax for creating the mySQL table we are inserting rows into:

CREATE TABLE avg_tally
(
AVG_ID INT NOT NULL AUTO_INCREMENT,
average FLOAT,
filename CHAR(6),
meta_desc VARCHAR(150),
PRIMARY KEY(AVG_ID)
);

You may notice the field "float" this is the field to use for floating point numbers. Also the use of the meta description which we grab as a better explanation for what the diary entry is about. We've already converted the $average into only having two decimal places by using the sprintf function.

The second step - modify the average function

We need to get the average function I created 7 months ago and provide a slight modification to it. We are going to call this new code function average2. The original code explanation for this is located here: 122699, but here is the code again that we are going to modify:

<?
function average2($filename)
{
 
global $average;
  $x= -1;
    if($file = fopen("$path/$filename", "r"))
   {
      while(!feof($file))
     {
      $therate = fgetss($file, 255);
      $x++;
      $count = $count + $therate;
     }
    fclose($file);
   }
$average = ($count / $x);
return ($average);
}
?>

We are introducing a statement I believe we haven't discussed yet called global. When you create functions the variables themselves used inside these functions cannot be used outside the function unless you use the global statement for the variable(s). In the case above by reviewing the red text you will see I have made sure we could return the value of $average instead of printing it like we do in the previously created average function. This is a better example of a function anyway since we wouldn't want to confine ourselves like I did in the original average function. Now with the new average2 function we can print the average, save the average to file, do whatever we want to do with this result. In our case, we are going to insert the average into the $avgs array. In the next diary I'll go through how to sort and display the results to complete this script in an alternating color table.

Example #28: Update and populate a mySQL database using a loop with the most current rating information
                      View source code of example #28

Please vote on the usefulness of this diary entry so other people will know if it is worth their time to read :)

How useful was this diary entry? Avg Surfer Rating: 3.88 (242)

[back]go back 07/30/00 "Functions, globals,  mySQL, brief object oriented programming" go forward[next]

PHP Diary | scriptschool.com | PHP Scripts | TD Scripts.com

Copyright 2000 php-scripts.com Last Modified 08/3/00 07:55