title: How to optimize a database connection and query, to prevent MySQL run out of memory?
body: <p>I have a class for my db connection, witch i try to use in order to limit the amount of connections to the server.</p>
  
  <p>If i have a lot of users, the sql server crash due to run out of memory. it can be the server setup, or it can be related to the code? i would appreciate any suggestions here.</p>
  
  <p>The __destruct kills the connection, but does it free the result in order to take on more query's?</p>
  
  <p>I'm leaving the example code here:</p>
  
  <pre><code>class db{
  
      public $db_connection;
  
  
      public function __construct(){
  
          $this-&gt;db_connection = new mysqli("127.0.0.1","myuser","passwd","dbname");
          $this-&gt;db_connection-&gt;set_charset("utf8");
  
          if($this-&gt;db_connection-&gt;connect_errno) {
              echo "Failed to connect to database: " . $db_connection-&gt;connect_error;
          }
      }
  
      public function __destruct(){
          return $this-&gt;db_connection-&gt;close();
      }
  }
  </code></pre>
  
  <p>Initiate the db connection, usally i do this in header, so i can re-use the connection troughout the page.</p>
  
  <pre><code>$db = new db();
  </code></pre>
  
  <p>Typical query on a random page: (can be more on one page)</p>
  
  <pre><code>&lt;div class="container"&gt;
      &lt;div class="row"&gt;
          &lt;div class="col-md-12"&gt;
              $result = $db-&gt;db_connection-&gt;query("SELECT * FROM news");
              if ($result) { 
                  while ($obj = $result-&gt;fetch_object()) {    
                      //some html code here
                  }
              }
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>