title: SQLSTATE[HY000] [2002] Connection timed out
body: <p>Getting this in my error logs every now and then and want to figure out the issue :</p>
  
  <blockquote>
    <p>[04-Oct-2014 13:25:42 America/Chicago] Failed to connect to database:
    SQLSTATE[HY000] [2002] Connection timed out [04-Oct-2014 13:25:42
    America/Chicago] PHP Fatal error:  Call to a member function prepare()
    on a non-object in /home/spconlin/public_html/spc_app/app/add_log.php
    on line 28</p>
  </blockquote>
  
  <p><strong>Connect script :</strong></p>
  
  <pre><code>&lt;?php
  
  if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');
  
  // db config
  $db_host        = '127.0.0.1';
  $db_database    = '*****';
  $db_user        = '*****';
  $db_pass        = '*****'; 
  
  //db connection
  try {
      $db = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_pass, 
          array(
              PDO::ATTR_EMULATE_PREPARES =&gt; false, 
              PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, //PDO::ERRMODE_SILENT is default setting
              PDO::ATTR_PERSISTENT =&gt; false
              )
      );
  }
  catch(PDOException $e) {
      error_log("Failed to connect to database: ".$e-&gt;getMessage());
  }
  
  ?&gt;
  </code></pre>
  
  <p><strong>What I have done :</strong></p>
  
  <ul>
  <li>switch from 'localhost' to 127.0.0.1 in the connection</li>
  <li>switch persistent connections to false</li>
  </ul>
  
  <p>Before doing the above changes to my connection I was getting <code>SQLSTATE[HY000] [2002] Resource temporarily unavailable</code> rather than <code>connection timed out</code> as shown above.</p>
  
  <p>Some background information - this add_log.php script in particular is adding information to the database up to a few times a second when it is actually being used.  While almost 99% of the time this particular script is referenced in the error sometimes other ones are.  I realize that the script pointed to really does not mean anything because this is not where the error is occurring (it occurs in the connection not the add_log.php script), but it is odd it is almost always this particular file referenced which leads me to believe the fact it is called so often in succession is part of the problem.</p>
  
  <p>DB is innodb.</p>
  
  <p>Is this actually a problem with my server and db or the person/computer connecting to it?  Is it possible 'they' have a bad connection to 'me' and this is what causes the error?</p>
  
  <p><strong>EDIT :</strong></p>
  
  <p>Could it be in the manner which I am requiring my connect script on pages it is needed?  Since the file is 'hit' quite often it would also be requiring my connect script just as much by the line below.  Note that I am using <code>$_SERVER['DOCUMENT_ROOT']</code> (could that have an affect?).</p>
  
  <blockquote>
    <p>require $_SERVER['DOCUMENT_ROOT'].'/custom/functions/connect.php';</p>
  </blockquote>