title: PHP mysqli->real_escape_string when using sessions saved in the DB
body: <p>Ok, I hope I've got everything listed up nicely before posting this question because I've found bits and pieces of a solution here and there but no real answer to my issue.</p>
  
  <p>1: I'm using a singleton MySQL connection with mysqli, not using stored procedures;</p>
  
  <p>2: I found code online explaining session_set_save_handler and have embedded it as a class called MySqlSessionStore;</p>
  
  <p>3: in my DB class there is this public function:</p>
  
  <pre><code>public function escapeStringForDB($input)
   {
    return $this-&gt;_link-&gt;real_escape_string($input);
   }
  </code></pre>
  
  <p>and <code>$this-&gt;_link = new mysqli($host, $user, $password, $database)</code></p>
  
  <p>4:<code>$db = MySQL::getInstance(array(DB_SERVER, DB_USER, DB_PASS, DB_NAME));</code>
  This is how I call the static DB function (nothing out of the ordinary here)</p>
  
  <p><strong>Problem</strong>: everything works until I uncomment <code>$id = $db-&gt;escapeStringForDB($id);</code>, then the following error occurs:</p>
  
  <p><strong>Call to a member function real_escape_string() on a non-object</strong></p>
  
  <p>Example code from MySqlSessionStore:</p>
  
  <pre><code>function read($id)
  {
      $db = MySQL::getInstance(array(DB_SERVER, DB_USER, DB_PASS, DB_NAME));
      $id = $db-&gt;escapeStringForDB($id);
      $db-&gt;query("SELECT data FROM sessions WHERE BINARY id = '". $id ."'");
      //echo "SELECT data FROM sessions WHERE id = '". $id ."'";
      $result = $db-&gt;fetch();
  
  
      if(isset($result) &amp;&amp; !empty($result))
      {
          return $result-&gt;data;
      }
      //MUST send an empty string if no session data
      return "";
  }
  </code></pre>
  
  <p>Other questions, remarks:</p>
  
  <ul>
  <li>I'm using session_regenerate_id() but apparently this needs to be removed with session_set_save_handler;</li>
  <li>Where exactly do I put <code>session_write_close();</code> ? I've got it in the destructor of my db class, but maybe that isn't the way to go;</li>
  <li>I'm using this without harm on other projects, but here it seems the session handler behavior is different and confusing me :)</li>
  </ul>
  
  <p>Thanks in advance, if you need more info I'll gladly provide it.</p>