title: PHP Data Objetcs (PDO) example
body: <p>I'm fairly new to object oriented programming in php, I just wrote the following script to create a connection using PDO and run a simple Select Query. It works fine, i just need to know if i have done it right! (need to know the best practices i'm missing).</p>
  
  <pre><code>&lt;?php
  class Connection
  {
      protected $host = "localhost";
      protected $username = "admin";
      protected $password = "admin";  
      protected $database = "thedatabase";
      protected $dsn;
      protected $dbh;
      protected $opt = array(PDO::ATTR_ERRMODE=&gt; PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE=&gt; PDO::FETCH_ASSOC);
      protected $error_found = false;
      protected $error_message;
  
      function __construct()
      {
          $this-&gt;dsn = "mysql:host=$this-&gt;host;dbname=$this-&gt;database;charset=utf8";
          try
          {
              $this-&gt;dbh = new PDO($this-&gt;dsn, $this-&gt;username, $this-&gt;password, $this-&gt;opt);
          }
          catch (PDOException $e)
          {
              $this-&gt;error_message = $e-&gt;getMessage();
              $this-&gt;error_found = true;
          }
      }
      public function closeConnection()
      {
          $this-&gt;dbh = null;
      }
      public function errorsFound()
      {
          if ($this-&gt;error_found == true) 
          {
              return true;
          }
          else
          {
              return false;
          }
      }
      public function showError()
      {
          return $this-&gt;error_message;
      }
  }
  
  class Model extends connection
  {
      public function select()
      {
          $sth = $this-&gt;dbh-&gt;query("SELECT * FROM `users`");
          $sth-&gt;setFetchMode(PDO::FETCH_ASSOC);
          while($row = $sth-&gt;fetch())
          {
              echo $row['username']."\r\n";
              echo $row['password']."\r\n";           
          }
      }
  }
  
  $connection = new Connection;
  if ($connection-&gt;errorsFound()==true) 
  {
      $error_messages = "Error: ".$connection-&gt;showError();
      echo $error_messages;
      $connection-&gt;closeConnection(); 
  }
  else
  {
      $model = new Model;
  
      $model-&gt;select();
      $connection-&gt;closeConnection();
  }
  ?&gt;
  </code></pre>