title: Setting up a database connection class in PHP
body: <p>I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases  I am still confused with. For example,</p>
  
  <p>Below is an example of how I would normally connect to my database and display information from user id's in a table</p>
  
  <p><strong>dbcon.php:</strong></p>
  
  <pre><code>&lt;?php
  $con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
  
  require_once("functions.php");
  ?&gt;
  </code></pre>
  
  <p><strong>functions.php</strong></p>
  
  <pre><code>function getUserInfo($id) {
      $query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
      return mysqli_fetch_array($query);
  }
  </code></pre>
  
  <p><strong>Some random file:</strong></p>
  
  <pre><code>require_once("dbcon.php");
  
  $result = mysqli_query($con, "SELECT * FROM tablename");
  while ($row = mysqli_fetch_assoc($result)) {
      $userinfo = getUserInfo($row['userid']);
      echo $userinfo['name'];
  }
  
  ?&gt;
  </code></pre>
  
  <p>I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read <a href="https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17" rel="noreferrer">this</a> article about using classes to tamper with a database and call functions that I created in the class.</p>
  
  <p>My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?</p>
  
  <p>I also would like to know what the <em>best</em> way to store my connection to the database is, and if there are any tutorials on how to set that up.</p>
  
  <p>I hope you understood that lol.</p>