Making a database class in PHP OOP way



To build a simple Database Class in PHP and MySQL use the following code:

<?php
class Database {

  public 
$mysql;

  function 
__construct()
  {
    
$this->mysql = new mysqli(hostuserpassworddb) or die('There was a problem connecting to the db');
  }

  function 
multiLine($sql)
  {
    
$this->mysql->query("SET NAMES 'utf8'");
    
$this->mysql->query("SET CHARACTER SET 'utf8'");

    if((
$result $this->mysql->query($sql)) != NULL) {
      
$x = array();
      while(
$row $result->fetch_array()) {
        
$x[] = $row;
      }
      return 
$x;
    }
    else {
      echo 
$this->mysql->error;
    }
  }


  function 
singleLine($sql)
  {

      
$one = array();
      if((
$result $this->mysql->query($sql)) != NULL)
      {
          
$one $result->fetch_array(); 
      }

      return 
$one;
  }

  function 
__destruct() {
    
// close out the database connection;
    
$this->mysql->close();
  }
}
?>

Now multiline function would work like:

<?php
$db 
= new Database();
$sql 'SELECT * FROM users ORDER BY id DESC';

$response $db->multiLine($sql);

<?
php foreach($response as $r) : ?>
<p>ID: <?php echo $r['id']; ?></p>
<p>Username: <?php echo $r['username']; ?></p>
<?php endforeach; ?>



Mysqli is already a class, so if you want to simplify or add functions, extend it.

See following article, http://devzone.zend.com/article/687.