title: PHP Prevent multiple MySQL Connections
body: <p>I have a large procedural style php/mysql website, which is splitted into many different files. Within each file, i include my dbconn.php, to ensure, that a db connection is available.</p>
  
  <p>It looks something likes this:</p>
  
  <p>index.php</p>
  
  <pre><code>&lt;?php 
     include_once ('header.php');
     include_once ('nav.php');
     include_once ('content.php');
     include_once ('sidebar.php');
     include_once ('footer.php');
  ?&gt;
  </code></pre>
  
  <p>and within each of these files i call several other files via include_once. So in total i come up with about 30 different files.</p>
  
  <p>Every file starts with:</p>
  
  <pre><code>include_once($_SERVER['DOCUMENT_ROOT'].'/dbconn.php');
  </code></pre>
  
  <p>Since i'm using include_once, dbconn.php should not be loaded more then once, but recently i get following php warning.</p>
  
  <pre><code>PHP Warning:  mysqli_connect(): (HY000/1226): User 'username' has exceeded the 'max_user_connections' resource (current value: 20) in /var/www/html/dbconn.php on line 10
  </code></pre>
  
  <p>My dbconn.php looks like this:</p>
  
  <pre><code>&lt;?php
     $host = "localhost";
     $user = "username";
     $pass = "password";
     $db = "dbname";
  
     if(!mysqli_thread_id($con)){
         $con = mysqli_connect($host, $user, $pass, $db);
         mysqli_set_charset($con, 'utf8');
     }
     unset($host,$user,$pass,$db);
  ?&gt;
  </code></pre>
  
  <p>So there is a double check.
  If there already is an open mysql connection, the file should do basicly nothing.</p>
  
  <p>What am i doing wrong?
  Why do i get this php warning and how do i reduce the amount of mysql connections?</p>