title: How to convert mysql to mysqli database connection in the constructor
body: <p>I am just trying to convert mysql to mysqli database connection in the constructor.</p>
  
  <p>db.php</p>
  
  <pre><code>&lt;?php
  define('SERVER', 'localhost');
  define('USERNAME', 'root');
  define('PASSWORD', 'password');
  define('DATABASE', 'database');
  class DB {
      function __construct(){
          $connection = mysqli_connect(SERVER, USERNAME, PASSWORD,DATABASE);
      }
  }
  ?&gt;
  </code></pre>
  
  <p>users.php</p>
  
  <pre><code>&lt;?php
  class Users {
      function __construct(){
          $db = new DB();
      }
  
      public function read(){
          $query = mysqli_query($db,"select use_id, use_name, use_email FROM users");
          while ($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
              $data[] = $row;
          }
          return $data;
      }
  }
  ?&gt;
  </code></pre>
  
  <p>result.php</p>
  
  <pre><code>&lt;?php require_once('db.php'); ?&gt;
  &lt;?php require_once('users.php'); ?&gt;
  &lt;?php
  $Users = new Users();
  $users = $Users-&gt;read();
  ?&gt;
  </code></pre>
  
  <p>I tried changing mysql to mysqli methods, but it is not connecting and I read somewhere that instantiate the db connection in the constructor is a bad idea: please, can you explain why, and if there's a better way to have the db connection easily available in every class that needs it?</p>