Building A Dynamic MySQL Paging Class With PHP - The RecNav constructor
(Page 3 of 6 )
Before we jump into how the RecNav constructor works, note that our RecNav class contains a number of variables, each prefixed with two underscores:
var $__linkId;
var $__dbType;
var $__query;
var $__template;
var $__templateHeader;
var $__templateFooter;
var $__recsPerPage;The RecNav constructor really only validates the parameters passed to it, assigning default values to them if they're out of range or of the wrong type, etc. The constructor starts by making sure that the link identifier parameter is valid, by sending a dummy query to the MySQL server:
// Validate constructor parameters
if(!@mysql_query("SELECT 1", $LinkIdentifier))
{ die("MYSQL link identifier is invalid"); }
else
{
$this->__linkId = $LinkIdentifier;
}If the link identifier isn't valid then the constructor calls the die() function with an error message. If the link identifier is valid, the __linkId variable is assigned its reference. Next, we validate the $Query parameter with a regular expression. It must contain "SELECT" as its first characters in order for it to be considered valid:
if(!ereg("^SELECT", $Query))
{ die("Invalid query: query must start with 'SELECT'"); }
else
{ $this->__query = $Query; }The three template variables are then validated. If they are passed in, but passed as empty, then they are given default values that are defined within the same file as the class:
if($Template == "")
{ $this->__template = DEFAULT_TEMPLATE; }
else
{ $this->__template = $Template; }
if($TemplateHeader == "")
{ $this->__templateHeader = DEFAULT_TEMPLATE_HEADER; }
else
{ $this->__templateHeader = $TemplateHeader; }
if($TemplateFooter == "")
{ $this->__templateFooter = DEFAULT_TEMPLATE_FOOTER; }
else
{ $this->__templateFooter = $TemplateFooter; }Lastly, we make sure that the $RecsPerPage parameter is numeric and valid. We then assign its value to the __recsPerPage variable:
if(!is_numeric($RecsPerPage) || $RecsPerPage < 1)
{ $this->__recsPerPage = DEFAULT_NUM_RECS; }
else
{ $this->__recsPerPage = $RecsPerPage; }That's all of the code for the RecNav constructor. Because the constructor is so flexible, we can call it in a number of different ways:
// Return 10 records per page
$r = new RecNav($s, "SELECT * FROM books ORDER BY bookId ASC", "", "", "", 10);
// Return the default number of records and use default templates:
$r = new RecNav($s, "SELECT * FROM books");
// Return 20 records and use custom record template
$r = new RecNav($s, "SELECT * FROM books", "", "<tr><td><| row0 |></td></tr>", "", 20);Next: The ShowRecs function >>
More MySQL Articles
More By Joe O'Donnell