title: PHP Warning: mysqli::query(): Couldn't fetch mysqli
body: <p>Here's my current code:</p>
  
  <pre><code>&lt;?php 
  $key = $_REQUEST['key'];
  $url = $_REQUEST['url'];
  
  include_once '../../dbconnect.php';
  
  $query = $conn-&gt;query("SELECT * FROM members WHERE apikey='$key' &amp;&amp; status='Active'");
  $userRow=$query-&gt;fetch_array();
  $conn-&gt;close();
  
  /// Verify the URL starts with http:// or https://
  if (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://')) {
  $url = $url;
  } else {
  $url = "http://$url";
  }
  
  /// Verify the key is 32 characters
  if (!preg_match('/[^A-Za-z0-9]/', $key) &amp;&amp; (strlen($key) == 32)) {
  
  /// Verify the URL isn't malicious
  if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
      die('Error:  Invalid URL');
  } else {
  
  if ($userRow['status'] === 'Active') {
  
  function generateRandomString($length = 8) {
      $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      $charactersLength = strlen($characters);
      $randomString = '';
      for ($i = 0; $i &lt; $length; $i++) {
          $randomString .= $characters[rand(0, $charactersLength - 1)];
      }
      return $randomString;
  }
  
  $redirect = generateRandomString();
  
  $addshort = $conn-&gt;query("INSERT INTO short_".$redirect[0]." (redirect, apikey, url) VALUES ('".$redirect."','".$key."','".$url."')");
  
  if ($conn-&gt;query($addshort) === TRUE) {
  echo "added correctly";
  } else {
  echo "there was an error";
  }
  
  $conn-&gt;close();
  
  } else {
  echo "Error:  Account Not Active";
  }
  
  }
  
  } else {
  die('Error:  Invalid API Key');
  }
  ?&gt;
  </code></pre>
  
  <p>Here's the error_log:</p>
  
  <pre><code>[18-Oct-2016 12:21:31 America/New_York] PHP Warning:  mysqli::query(): Couldn't fetch mysqli in /home/username/public_html/subdomains/url/index.php on line 40
  [18-Oct-2016 12:21:31 America/New_York] PHP Warning:  mysqli::query(): Empty query in /home/username/public_html/subdomains/url/index.php on line 42
  [18-Oct-2016 12:21:31 America/New_York] PHP Warning:  mysqli::close(): Couldn't fetch mysqli in /home/username/public_html/subdomains/url/index.php on line 48
  </code></pre>
  
  <p>You can see on the 7th line where I connect to the database for the first time:</p>
  
  <pre><code>$query = $conn-&gt;query("SELECT * FROM members WHERE apikey='$key' &amp;&amp; status='Active'");
  </code></pre>
  
  <p>And that line is working.  However, the second time I'm connecting to do an <code>INSERT</code>, I'm getting the above errors:</p>
  
  <pre><code>$addshort = $conn-&gt;query("INSERT INTO short_".$redirect[0]." (redirect, apikey, url) VALUES ('".$redirect."','".$key."','".$url."')");
  </code></pre>
  
  <p>Is there something I'm missing from just staring at this code for too long?</p>