Article

The PHP Anthology Volume I, Chapter 3 - PHP and MySQL

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Next

Reusable Code

You've just seen the most simplistic way to connect to MySQL. It's often more useful, however, to "package" the above code in a function or a class so it can be reused.

As a function we could have:

Example 3.3. 2.php  
 
<?php  
function &connectToDb($host, $dbUser, $dbPass, $dbName)  
{  
 // Make connection to MySQL server  
 if (!$dbConn = @mysql_connect($host, $dbUser, $dbPass)) {  
   return false;  
 }  
 
 // Select the database  
 if (!@mysql_select_db($dbName)) {  
   return false;  
 }  
 
 return $dbConn;  
}  
 
$host   = 'localhost'; // Hostname of MySQL server  
$dbUser = 'harryf';    // Username for MySQL  
$dbPass = 'secret';    // Password for user  
$dbName = 'sitepoint'; // Database name  
 
$dbConn = &connectToDb($host, $dbUser, $dbPass, $dbName);  
?>

This reduces the process of connecting to MySQL and selecting a database to a single line (two if you count the include statement, which would point to a separate file containing the connectToDb function):

$dbConn = &connectToDb($host, $dbUser, $dbPass, $dbName);

Note that we've used the reference operator &. This operator and the role it plays were covered in detail in Chapter 2, Object Oriented PHP.

Be Lazy: Write Good Code!

Scientists have now conclusively proven that knowledge of PHP is inversely proportional to free time but directly proportional to hair loss. The only way to prevent these effects is to learn how to write scalable, maintainable, and reusable code as early as possible. Taking advantage of classes and object orientation in PHP is a big step in the right direction. As a PHP developer, laziness is a virtue.

Going a step further, we can wrap this code in a class:

Example 3.4. Database/MySQL.php (in SPLIB) (excerpt)  
 
/**  
* MySQL Database Connection Class  
* @access public  
* @package SPLIB  
*/  
class MySQL {  
 /**  
  * MySQL server hostname  
  * @access private  
  * @var string  
  */  
 var $host;  
 
 /**  
  * MySQL username  
  * @access private  
  * @var string  
  */  
 var $dbUser;  
 
 /**  
  * MySQL user's password  
  * @access private  
  * @var string  
  */  
 var $dbPass;  
 
 /**  
  * Name of database to use  
  * @access private  
  * @var string  
  */  
 var $dbName;  
 
 /**  
  * MySQL Resource link identifier stored here  
  * @access private  
  * @var string  
  */  
 var $dbConn;  
 
 /**  
  * Stores error messages for connection errors  
  * @access private  
  * @var string  
  */  
 var $connectError;  
 
 /**  
  * MySQL constructor  
  * @param string host (MySQL server hostname)  
  * @param string dbUser (MySQL User Name)  
  * @param string dbPass (MySQL User Password)  
  * @param string dbName (Database to select)  
  * @access public  
  */  
 function MySQL($host, $dbUser, $dbPass, $dbName)  
 {  
   $this->host = $host;  
   $this->dbUser = $dbUser;  
   $this->dbPass = $dbPass;  
   $this->dbName = $dbName;  
   $this->connectToDb();  
 }  
 
 /**  
  * Establishes connection to MySQL and selects a database  
  * @return void  
  * @access private  
  */  
 function connectToDb()  
 {  
   // Make connection to MySQL server  
   if (!$this->dbConn = @mysql_connect($this->host,  
       $this->dbUser, $this->dbPass)) {  
     trigger_error('Could not connect to server');  
     $this->connectError = true;  
   // Select database  
   } else if (!@mysql_select_db($this->dbName,$this->dbConn)) {  
     trigger_error('Could not select database');  
     $this->connectError = true;  
   }  
 }  
 
 /**  
  * Checks for MySQL errors  
  * @return boolean  
  * @access public  
  */  
 function isError()  
 {  
   if ($this->connectError) {  
     return true;  
   }  
   $error = mysql_error($this->dbConn);  
   if (empty($error)) {  
     return false;  
   } else {  
     return true;  
   }  
 }

Now that may seem pretty overwhelming, but what's most important is not how the class itself is coded (the trigger_error function will be discussed in the section called "How do I resolve errors in my SQL queries?" later in this chapter), but how you use it.

What's most important is that the task of connecting to MySQL is now reduced to the following:

Example 3.5. 3.php  
 
<?php  
// Include the MySQL class  
require_once 'Database/MySQL.php';  
 
$host   = 'localhost'; // Hostname of MySQL server  
$dbUser = 'harryf';    // Username for MySQL  
$dbPass = 'secret';    // Password for user  
$dbName = 'sitepoint'; // Database name  
 
// Connect to MySQL  
$db = &new MySQL($host, $dbUser, $dbPass, $dbName);  
?>

The point of using a class here is to get some practice using PHP's object model to deal with common tasks. If you're new to object oriented programming with PHP, the most important thing to remember at this stage is that you don't need to understand all the code you find in a class to be able to use it in your code.

We'll be making use of this class and others throughout the book to illustrate how object oriented programming aids the reuse of code and can save time when you're developing applications.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article