title: Connecting to a MySQL database with PDO
body: <p>Pre-emptive apology: This post contains basic questions.However, I have searched and I have not found an answer, if there is one...sorry. </p>
  
  <p>I am following some youtube tutorials for making a basic ajax web chat, and in the tutorial the person is using MySQLi to connect to the DB. I want to create the same ajax chat application except I want to use PDO instead of MySQLi.</p>
  
  <p>The person uses these two files:</p>
  
  <p><strong>config.php</strong></p>
  
  <pre><code>&lt;?php
    define('DB_HOST', 'localhost');
    define('DB_USER', 'bucky_chat');
    define('DB_PASSWORD', '123456');
    define('DB_NAME', 'bucky_chat');
  ?&gt;`   
  </code></pre>
  
  <p><strong>chat.class.php</strong></p>
  
  <pre><code>&lt;?php
     require_once('config.php');
     require_once('error_handler.php');
  
  class Chat {
  
      private $mysqli;
  
      //constructor opens DB connection
      function __construct(){
          $this-&gt;mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
      }
  
      //destructor closes db connection
      function __destruct(){
          $this-&gt;mysqli-&gt;close();
      }
  
  }
  
  ?&gt;
  </code></pre>
  
  <p>I'm trying to replicate the above snippets with PDO. The problem is that I'm not sure how to adapt the PDO examples I have looked at to do this.</p>
  
  <p>First of all I'm confused as to why he defined these things in a separate file.. are there any benefits in doing this?</p>
  
  <p>In another PDO tutorial I am looking at I see it can be done the followings way:</p>
  
  <pre><code>&lt;?php
  $config['db'] = array(
  'host' =&gt; 'localhost',
  'username' =&gt; '',
  'password' =&gt; '',
  'dbname' =&gt; ''
  );
  
  $db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['db_name'], $config['db']['username'], $config['db']['password']);
  //some code
  $db = null; //closes connection
  ?&gt;
  </code></pre>
  
  <p>`</p>
  
  <p>I <em>think</em> this is what I need to use (in a try catch block), but why does he put these things in an array? it seems to over complicate things... why not just variables? But does this code replicate the mysqli example? Howcome I don't see __construct() being used with PDO?</p>
  
  <p>Some minor questions...
  When creating a website with a user, is there a standard place to store DB connection?
  Any book recommendations?</p>
  
  <p>Sorry for all these questions, All help is strongly appreciated!</p>