title: Warning: mysqli_query(): Couldn't fetch mysqli
body: <p>I am new to PHP and not familiar with many of its rules, so this could possibly be a stupid question.</p>
  
  <p>I have a database with top level categories and subcategories combined into one table. I want to first print out all the top-level categories, and then printout the subcategories associated with that category. </p>
  
  <p>Here is my code:</p>
  
  <pre><code>&lt;?php
  session_start();
  
  include_once "/mysqli_connect.php";
  
  $categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
  
  
  mysqli_close($conn);
  ?&gt;
  
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta charset="UTF-8" /&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;div id="wrap" class="animate"&gt;
  
  &lt;?php 
  
  while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {
  
      $catecory_name = $categories['category'];
      echo '
      &lt;div class="content"&gt;
      &lt;div class="content_container no_padding"&gt;
      &lt;div class="content_container header"&gt;
      &lt;p&gt;'.$categories['category'].'&lt;/p&gt;
      &lt;/div&gt;
      ';
  
      $subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
  
      while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
          echo $subcategories['category'];
      //mysqli_free_result($subcategories0);
      }
  
      echo '
      &lt;/div&gt;
      &lt;/div&gt;
      ';
  
  }
  
   ?&gt;
  
  &lt;/div&gt;
  &lt;/div&gt;
  
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Here is the connection script:</p>
  
  <pre><code>&lt;?php
  
  DEFINE ('DB_USER', '*');
  DEFINE ('DB_PASSWD', '*');
  DEFINE ('DB_HOST', '*');
  DEFINE ('DB_NAME', '*');
  
  $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME);
  
  if(!$conn){
      die('Database connection error');
  }
  
  echo '&lt;!-- Connected to database --&gt;'
  
  ?&gt;
  </code></pre>
  
  <p>It returns the following error:</p>
  
  <pre><code>Warning: mysqli_query(): Couldn't fetch mysqli
  </code></pre>
  
  <p>When both queries are above the doctype everything is fine, but when the second query is below the doctype the error occurs. </p>
  
  <p>The first query always runs without problems, it is the second one that returns the error.</p>
  
  <p>I can't seem to figure out what is going on, if anyone can help me that would be appreciated.</p>