title: PHP Singleton Database Query
body: <p>In PHP, I have following Singleton Database Class:</p>
  
  <pre><code>class Database
  {
      private static $instance;
  
      private function __construct()
      {
          self::$instance = new mysqli('localhost', 'root', 'Matthias', 'financecontrol', '3307');
          if (!self::$instance) {
              throw new Exception('Could not connect to database in function __construct.');
          }
      }
  
      public static function getInstance()
      {
          if (!self::$instance) {
              self::$instance = new Database();
          }
          return self::$instance;
      }
  
  }
  </code></pre>
  
  <p>Whenever I try to perform a query on the database in another PHP file, for example to check whether a user already exists:</p>
  
  <pre><code>function userExists($username)
      {
          try {
              $connection = Database::getInstance();
  
              $result = $connection-&gt;query("select * from user where username='$username'");
              if (!$result) {
                  throw new Exception("Connection to database failed in function userExists.");
              }
              if ($result-&gt;num_rows &gt; 0) {
                  return true;
              } else {
                  return false;
              }
          } catch (Exception $ex) {
              $errorPager = new ErrorpageGenerator();
              $errorPager-&gt;generateErrorPage($ex-&gt;getMessage());
              return false;
          }
      }
  </code></pre>
  
  <p>I get an error message "PHP Fatal error: Call to undefined method Database::query() in User.php on line 44"</p>
  
  <p>I've tried adding a query function in the Database class, but that did not seem to fix the problem. Any ideas? Thanks</p>