Revision [10023]
This is an old revision of WikkaCountingRecords made by JavaWoman on 2005-07-16 13:09:15.
Counting Records
this page is a stub - more content will followThis is the development page for a new WikkaCore core method getCount().
There are numerous places in Wikka where we need to know "how many" of a certain thing there are in the database: how many pages, how many comments, how many pages owned by the logged-in user, ... etc. And there will be more.
Currently all these counts are retrieved via different methods: sometimes building a query and getting the count directly (the most efficient way); sometimes by using the LoadSingle() method after building a query, which is highly inefficient, as it effectively first asks MySQL to assign a name to the count and return records in an associative array, then retrieves the first (only!) item from the array or records, and finally retrieves the number from the associative array by name.
A single method
To avoid all this inconsistency and inefficiency, here is a simple method that does nothing but retrieve a count and return it as an integer.
The getCount() method
The following method is added to wikka.php right after the LoadAll() method:
/**
* Generic 'count' query.
*
* Get a count of the number of records in a given table that would be matched
* by the given (optional) WHERE criteria. Only a single table can be queried.
*
* @access public
* @uses Query()
*
* @param string $table required: (logical) table name to query;
* prefix will be automatically added
* @param string $where optional: criteria to be specified for a WHERE clause;
* do not include WHERE
* @return integer number of matches returned by MySQL
*/
function getCount($table,$where='') # JW 2005-07-16
{
// build query
$where = ('' != $where) ? ' WHERE '.$where : '';
$query = 'SELECT COUNT(*) FROM '.$this->config['table_prefix'].$table.$where;
// get and return the count as an integer
return (int)mysql_result($this->Query($query),0);
}
* Generic 'count' query.
*
* Get a count of the number of records in a given table that would be matched
* by the given (optional) WHERE criteria. Only a single table can be queried.
*
* @access public
* @uses Query()
*
* @param string $table required: (logical) table name to query;
* prefix will be automatically added
* @param string $where optional: criteria to be specified for a WHERE clause;
* do not include WHERE
* @return integer number of matches returned by MySQL
*/
function getCount($table,$where='') # JW 2005-07-16
{
// build query
$where = ('' != $where) ? ' WHERE '.$where : '';
$query = 'SELECT COUNT(*) FROM '.$this->config['table_prefix'].$table.$where;
// get and return the count as an integer
return (int)mysql_result($this->Query($query),0);
}
As can be seen from the comment, all we pass to the method is the logical table name to query, and optionally the criteria to be used in a WHERE clause. The method builds a query adding the missing bits and returns the result (making sure it is an integer).
Doing it consistently
Now, with the getCount() method we have the tool to consistently and efficiently retrieve record counts where needed. Let's first look at where this can be used in the current 1.1.6.0 release.
Wikka Core
There is one method in the WikkaCore Wikka Core where a count of records is used, so we can aply the new method here.
ExistsPage() method
Current code:- /**
- * Check by name if a page exists.
- *
- * @author {@link http://wikka.jsnx.com/JavaWoman JavaWoman}
- * @copyright Copyright © 2004, Marjolein Katsma
- * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
- * @version 1.0
- *
- * @access public
- * @uses Query()
- *
- * @param string $page page name to check
- * @return boolean TRUE if page exists, FALSE otherwise
- */
- function ExistsPage($page)
- {
- $count = 0;
- $query = "SELECT COUNT(tag)
- FROM ".$this->config['table_prefix']."pages
- if ($r = $this->Query($query))
- {
- }
- return ($count > 0) ? TRUE : FALSE;
- }
This can now be rewritten as:
/**
* Check by name if a page exists.
*
* @author {@link http://wikka.jsnx.com/JavaWoman JavaWoman}
* @copyright Copyright © 2004, Marjolein Katsma
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @version 1.1
*
* @access public
* @uses getCount()
*
* @param string $page page name to check
* @return boolean TRUE if page exists, FALSE otherwise
*/
function ExistsPage($page)
{
$where = "`tag` = '".mysql_real_escape_string($page);."'";
$count = $this->getCount('pages',$where);
return ($count > 0);
}
* Check by name if a page exists.
*
* @author {@link http://wikka.jsnx.com/JavaWoman JavaWoman}
* @copyright Copyright © 2004, Marjolein Katsma
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @version 1.1
*
* @access public
* @uses getCount()
*
* @param string $page page name to check
* @return boolean TRUE if page exists, FALSE otherwise
*/
function ExistsPage($page)
{
$where = "`tag` = '".mysql_real_escape_string($page);."'";
$count = $this->getCount('pages',$where);
return ($count > 0);
}
Actions
actions/countcomments.php
Current code:- <?php
- /**
- * Print total number of comments in this wiki.
- */
- $commentsdata = $this->LoadSingle("SELECT count(*) as num FROM ".$this->config["table_prefix"]."comments");
- echo $commentsdata["num"];
- ?>
This can now be rewritten as:
- <?php
- /**
- * Print total number of comments in this wiki.
- */
- echo $this->getCount('comments');
- ?>
actions/countowned.php
Current code:- <?php
- /**
- * Print number of pages owned by the current user.
- */
- $str = 'SELECT COUNT(*) FROM '.$this->config["table_prefix"].'pages WHERE `owner` ';
- $str .= "= '" . $this->GetUserName() . "' AND `latest` = 'Y'";
- $countquery = $this->Query($str);
- ?>
This can now be rewritten as:
- <?php
- /**
- * Print number of pages owned by the current user.
- */
- $where = "`owner` = ".$this->GetUserName()." AND `latest` = 'Y'";
- $count = $this->getCount('pages',$where);
- ?>
actions/countpages.php
Current code:- <?php
- /**
- * Print the total number of pages in this wiki.
- */
- $pagedata = $this->LoadSingle("SELECT count(*) as num FROM ".$this->config["table_prefix"]."pages WHERE latest = 'Y'");
- ?>
This can now be rewritten as:
- <?php
- /**
- * Print the total number of pages in this wiki.
- */
- $where = "`latest` = 'Y'";
- $count = $this->getCount('pages',$where);
- ?>
actions/countusers.php
Current code:- <?php
- /**
- * Print number of registered users.
- */
- $userdata = $this->LoadSingle("SELECT count(*) as num FROM ".$this->config["table_prefix"]."users ");
- echo $userdata["num"];
- ?>
This can now be rewritten as:
- <?php
- /**
- * Print number of registered users.
- */
- echo $this->getCount('users');
- ?>
actions/highscores.php
This uses the following code to get a 'total' count:- $str = 'SELECT COUNT(*) FROM '.$this->config["table_prefix"].'pages WHERE `latest` = \'Y\' ';
- $totalQuery = $this->Query( $str );
This can now be rewritten as:
- $where = "`latest` = 'Y'";
- $total = $this->getCount('pages',$where);
While this is actually the same query, we'd use the getCount() method here for consistency (and hiding cmplexity).
actions/lastusers.php
This prints the number of pages owned by a particular (new) user as follows:- if ($stat!=="0") $num = $this->LoadSingle("select count(*) as n from ".$this->config["table_prefix"]."pages where owner='".$user["name"]."' AND latest = 'Y'");
- $htmlout .= " <td>".$this->Link($user["name"])."</td>\n <td>".($stat!=="0"?" . . . . . (".$num["n"].")":"")."</td>\n <td>(".$user["signuptime"].")</td>\n";
This can now be (better) rewritten as:
- if ($stat !== "0")
- {
- $where = "`owner` = '".$user['name']."' AND `latest` = 'Y'";
- $htmlout .= " <td>".$this->Link($user['name'])."</td>\n <td>"." . . . . . (".$this->getCount('pages',$where).")"."</td>\n <td>(".$user['signuptime'].")</td>\n";
- }
- else
- {
- $htmlout .= " <td>".$this->Link($user['name'])."</td>\n <td></td>\n <td>(".$user['signuptime'].")</td>\n";
- }
There are other ways in which this action can (and should) be improved but we're looking only at counting records here.
actions/ownedpages.php
This uses two counts. Current code:- $str = 'SELECT COUNT(*) FROM '.$this->config["table_prefix"].'pages WHERE `owner` ';
- $str .= "= '" . $this->GetUserName() . "' AND `latest` = 'Y'";
- $countQuery = $this->Query( $str );
- # get the total # of pages
- $str = 'SELECT COUNT(*) FROM '.$this->config["table_prefix"].'pages WHERE `latest` = \'Y\' ';
- $totalQuery = $this->Query( $str );
This can now be rewritten as:
- $whereowner = "`owner` = '" . $this->GetUserName() . "' AND `latest` = 'Y'";
- $wheretotal = "`latest` = 'Y'";
- $count = $this->getCount('pages',$whereowner);
- $total = $this->getCount('pages',$wheretotal);
As with the highscores action, this uses actually the same queries, but we use the getCount() method for the same reasons.
Beta features and proposed code
A number of current WikkaBetaFeatures beta features and other code proposed for a next release can also make good use of the getCount() method. We'll look at them here.
to follow
Todo
The method could be extended somewhat to make it more capable; for instance:
- allow the table parameter to be an array, and build the FROM clause using the list of table names
Comments?
As always, comments and suggestions more than welcome but please wait until this page is no longer marked as a stub.
CategoryDevelopmentCore CategoryDevelopmentActions CategoryDevelopmentHandlers