Generating Outputs from MySQL with Static Members and Methods in PHP 5

Trying to expand beyond the boundaries of your existing background by learning how to code and use static methods and properties inside your PHP 5 classes? Then look no further. Welcome to the last part of the series “Using static members and methods in PHP 5.” Made up of two instructive chapters, this series introduces the foundations of using static members and defines static methods in PHP 5-driven development environments.

Introduction

If you’re anything like me, then it’s quite probable that you’ve already included static members and methods in your PHP 5 classes, which means that you should consider yourself a fairly experienced developer.

On the other hand, for those who are completely new to the object model introduced with PHP 5, the subject in question is quite simple: essentially, static methods are those that are callable from outside the regular object context (using the :: scope resolution operator), and therefore can to be invoked without needing to use a specific class instance.

In addition, properties that have been declared static inside a class should be accessed from outside the object scope, via the “self” keyword, instead of using the $this pseudo variable. However, even though all these concepts may sound a bit intimidating, things are much simpler than you think, since declaring class methods and properties static is achieved by prefixing them with the “static” PHP keyword. That’s all.

Of course, as with most features of a specific programming language, using static members and methods needs to be taught by practical examples, which leads directly to the subject of this article. Since in the first tutorial you were provided with a couple of concrete cases where a class used a static property, as well as one static method (remember the definition of the Singleton class), in this tutorial you’ll see another example where these kinds of methods and members are properly utilized.

Specifically, I’ll show you how to use static methods to generate disparate outputs from MySQL database tables. If this topic sounds appealing to you, it’s time to get started. Let’s go!

{mospagebreak title=Working with MySQL}

Before I proceed to demonstrate how to use static methods for generating different outputs from a given MySQL database table, first I need to create a pair of classes that allow me to interact with the database server. Taking this into account, I listed the signature for these two classes below:

// define 'MySQL' class class MySQL{ private $conId; private $host; private $user; private $password; private $database; private $result; public function __construct($options=array()){         if(count($options)<4){ throw new Exception('Invalid number of connection
parameters');} foreach($options as $parameter=>$value){ if(!$value){ throw new Exception
('Invalid parameter '.$parameter);} $this->{$parameter}=$value;}   $this->connectDB();} private function connectDB(){ if(!$this->conId=mysql_connect($this->host,$this->user,
$this->password)){ throw new Exception('Error connecting to the server');} if(!mysql_select_db($this->database,$this->conId)){ throw new Exception('Error selecting
database');} } public function query($query){         if(!$this->result=mysql_query($query,$this->conId)){ throw new Exception('Error performing query '.$query);} return new Result($this,$this->result);} } // define 'Result' class class Result{ private $mysql; private $result; public function __construct(&$mysql,$result){        $this->mysql=&$mysql; $this->result=$result;} public function fetchRow(){ return mysql_fetch_assoc($this->result); } public function countRows(){        if(!$rows=mysql_num_rows($this->result)){ throw new Exception('Error counting rows'); } return $rows; } public function countAffectedRows(){        if(!$rows=mysql_affected_rows($this->mysql->conId)){ throw new Exception('Error counting affected rows');} return $rows;} public function getInsertID(){      if(!$id=mysql_insert_id($this->mysql->conId)){ throw new Exception('Error getting ID');} return $id;} public function seekRow($row=0){        if(!int($row)||$row<0){ throw new Exception('Invalid result set offset');}      if(!mysql_data_seek($this->result,$row)){ throw new Exception('Error seeking data');} } public function fetchFormattedResult($query,$closeTag='</p>'){ if(preg_match("/^SELECT/",$query)){ throw new Exception('Query must begin with SELECT');} $output=''; $opentag=str_replace('/','',$endTag);      while($row=$this->fetchRow()){         $output.=$openTag.$row.$closeTag;}         unset($openTag,$closeTag); return $output; } public function getResultSet(){ return $this->result; } }

 

In simple words, the above pair of classes will allow me to perform some useful tasks, like connecting to MySQL, running queries, handling data sets, and so forth, which is very convenient for generating different outputs from one or many database tables. However, definitely these classes aren’t the main subject of this article, therefore I don’t want you to get bored quickly reading my explanations about what they do.

Instead, now that the classes have been defined, let’s move on to the following section and learn more on how to create a few more understandable classes, where each of them will be responsible for generating different outputs from some MySQL database tables. And don’t you worry, because static methods are just around the corner, trust me!

In order to see how these brand new classes will be defined, please click on the link below and keep reading.

{mospagebreak title=Creating the ResultToString, ResultToXML and ResultToArray classes}

As the title of this section indicates, my intention consists basically of building up three different classes, where each of them will be tasked with taking up a given MySQL result set. They will then apply to it the proper conversion process; that is, they will turn the data set rows into plain strings, XML data and an associative array respectively. Finally, they will return the results to calling code.

All right, after explaining the main purpose of each one of the classes that I plan to create, it’s time to see how they look, right? I have listed their source code below, so check them out:

// define ‘ResultToString’ class

 

class ResultToString{

	private $result;

public function
__construct(Result $result){
	      
	$this->result=$result;

		}


// fetch result set as plain text


public function fetch(){

	$str='';
      
	while($row=$this->result->fetchRow()){

		foreach($row as $key=>$value){
	        
		$str.='['.$key.']='.$value."n";

				}

        	$str.='--------------------------'."n";

				}
		return $str;

		}

		}



// define 'ResultToXML' class

class ResultToXML{

		private $result;

public function
__construct(Result $result){

      	$this->result=$result;

			}

// fetch result set as XML


public function fetch(){

	$xml='<?xml
	version="1.0"
	encoding="iso-8859-1"?>'."n".'<data>'."n";

 

        while($row=$this->result->fetchRow()){        $xml.='<row>'."n"; foreach($row as $key=>$value){               $xml.='<'.$key.'>'.$value.'</'.$key.'>'."n"; }            $xml.='</row>'."n"; }         $xml.='</data>'."n"; return $xml; } } // define 'ResultToArray' class class ResultToArray{ private $result; public function __construct(Result $result){        $this->result=$result; } // fetch result set as array public function fetch(){ $data=array();       while($row=$this->result->fetchRow()){ $data[]=$row; } return $data; } }

 

As you’ll realize, the logic of the three classes shown above is fairly easy to understand. Essentially, each of them will accept an object of type “Result” inputted via the corresponding constructor. The object will be used from inside the class to convert a given MySQL result set to the corresponding format, that is plain strings, XML or an associative array.

With reference to the conversion process in question, this will be performed in all the previously defined classes by using their “fetch()” method, which obviously implements a different logic in accordance with the type of data that must be returned to calling code. Simple and efficient, isn’t it?

Okay, at this point I defined the pair of MySQL processing classes that you saw in a previous section, as well as the three that were created a few lines above and are handy for generating several outputs from a specific result set. However, until now I’ve not given you a single clue about how and why we will include static methods within the classes just defined. So, where will they be coded?

Fortunately, I have a good answer for that question. Since my primary objective is to generate disparate data formats from a single MySQL result set, the next step that I’m going to take will consist of creating an additional class, which will be capable of returning distinct data set processor objects  to produce the range of outputs that I mentioned before.

How will this be done? Yep, you guessed right. The entire process for returning result set processor objects to calling code will be handled by a static method! After all, we’re not far from reaching our goal, but this requires you to jump straight into the next section and continue reading. Thus, go ahead. I’ll be there, waiting for you.

{mospagebreak title=Defining the ResultProcessorFactory class}

As I said right at the beginning of this series, static methods let you perform specific tasks, without having to be restricted by the existence of a concrete class instance. In this particular case, I’m going to apply that concept to define a factory class, which will be responsible for fabricating result set processor objects.

Having said that, here is the corresponding definition for the entirely new “ResultProcessorFactory” class:

// define 'ResultProcessorFactory' class class ResultProcessorFactory{ static public function createResultProcessor($resultProcessor,
Result $result){        if(!preg_match
("/(ResultToString|ResultToXML|ResultToArray)/",$resultProcessor)){ throw new Exception('Invalid result
processor'); } return new $resultProcessor($result); } }

 

Undoubtedly, the class coded above won’t blow your mind away, since its signature is very simple. Basically, all that this class does is take the name of the result processor object being created and return this object to client code. Of course, this process is carried out by calling the long-awaited “createResultProcessor()” method, which has been defined as static.

In addition, it should be noticed that the method also accepts an object of type “Result,” which will be required further to create the appropriate result processor object.

Now that you know how the previous class looks, I’d like to show you a quick example that illustrates the complete process for generating different outputs from a specific MySQL result set, as well as for invoking the static “createResultProcessor()” method.

To begin with, suppose that you have a simple CUSTOMERS database table that has been populated with the following data:

1  Customer 1 customer1@domain.com

2  Customer 2 customer2@domain.com
3  Customer 3 customer3@domain.com
4  Customer 4 customer4@domain.com
5  Customer 5 customer5@domain.com

After filling in the sample database table with some basic information about hypothetical customers, please examine the script below, which uses the static “createResultProcessor()” method to generate different views from the respective database table:

try{

    // connect to MySQL

    $db=new MySQL(array
(‘host’=>’host’,’user’=>’user’,’password’=>’password’,’database’=>
‘database’));

    $result=$db->query(‘SELECT * FROM customers’);

    // create ‘ResultToString’ processor object

    //$resultString=ResultProcessorFactory::createResultProcessor
(‘ResultToString’,$result);

    header(‘Content-Type: text/plain’);

    echo $resultString->fetch();

    /* displays the following string of data

   
[id]=1
    [name]=Customer 1
    [email]=customer1@domain.com
   
--------------------------
    [id]=2
    [name]=Customer 2
    [email]=customer2@domain.com
   
--------------------------
    [id]=3
    [name]= Customer 3
    [email]=customer3@domain.com
   
--------------------------
    [id]=4
    [name]= Customer 4
    [email]=customer4@domain.com
   
--------------------------
    [id]=5
    [name]= Customer 5
    [email]=customer5@domain.com
   
--------------------------

*/

}

catch(Exception $e){

    echo $e->getMessage();

    exit();

}

As you can see, the first example uses the static “createResultProcessor()·” method to display the string of data show above. Again, I’d like to stress that no class instance has been created, since the method has been called from outside the object context.

Once you understand the previous example, take a look at the following one, which generates some XML nodes from the same result set:

 

try{

//connect to MySQL

	$db=new MySQL(array('host'=>'host','user'=>'user',
'password'=>'password','database'=>'database')); $result=$db->query('SELECT * FROM customers'); // create 'ResultToString' processor object //$resultString=ResultProcessorFactory::createResultProcessor
('ResultToString',$result); header('Content-Type:text/plain'); echo $resultString->fetch(); /* displays the following string of data
   
[id]=1
    [name]=Customer 1
    [email]=customer1@domain.com
   
--------------------------
    [id]=2
    [name]=Customer 2
    [email]=customer2@domain.com
   
--------------------------
    [id]=3
    [name]= Customer 3
    [email]=customer3@domain.com
   
--------------------------
    [id]=4
    [name]= Customer 4
    [email]=customer4@domain.com
   
--------------------------
    [id]=5
    [name]= Customer 5
    [email]=customer5@domain.com
   
--------------------------
*/ } catch(Exception $e){ echo $e->getMessage(); exit(); }

 

Finally, here is the last example, which returns the same MySQL result set as an associative array:

 

try{
    // connect to MySQL
    $db=new MySQL(array('host'=>'host','user'=>'user',
'password'=>'password','database'=>'database')); $result=$db->query('SELECT * FROM customers'); $resultArray=ResultProcessorFactory::createResultProcessor
('ResultToArray',$result); print_r($resultArray->fetch()); } catch(Exception $e){ echo $e->getMessage(); exit(); } /* displays the following: Array ( [0]=> Array ( [id]=> 1 [name]=> Customer1
[email]=> customer1@domain.com ) [1]=> Array ( [id]=> 2 [name]=>
Customer 2 [email]=>customer2@domain.com) [2]=> Array ( [id]=> 3
[name]=> Customer 3[email]=> customer3@domain.com ) [3]=> Array
( [id]=> 4 [name]=> Customer 4 [email]=> customer4@domain.com )
[4]=> Array ( [id]=> 5 [name]=> Customer 5 [email]=>
customer5@domain.com ) [5]) ) */

 

Final thoughts

In this two-part series, I walked you through the basics of using static members and methods with PHP 5. As you hopefully learned by the hands-on examples, if you need to call specific methods without having to deal with instances of a class, then static methods might be an option that you should take into account during the development of an application.

As usual, see you in the next PHP tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan