title: Proper way to call a custom php function from another file
body: <p>I would like to use custom functions that are all located in one file called functions.php that resides in the includes folder.</p>
  
  <p>A custom function inside functions.php is below and it seems to be working when I remove function <code>nos_check () {}</code> and load up functions.php alone.</p>
  
  <pre><code>function nos_check() {
      require_once ('config.php');
      mysql_connect($hostname,$dbusername,$dbpassword);
      @mysql_select_db($dbname) or die ("Unable to select database");
      $sql = mysql_query("SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ");
      $row = mysql_fetch_array($sql);
      // Assign how many sites the user has into a variable
      $how_many = $row['number_of_sites'];
      mysql_close();
          if ($how_many == 0) {
              echo 'You have no sites yet';
          } else {
              echo 'You have more than one site';
              }
      }
  </code></pre>
  
  <p>The file account.php is what's going to call that function:</p>
  
  <pre><code>include "includes/functions.php";
  nos_check();
  </code></pre>
  
  <p>I think I am probably calling the function incorrectly or perhaps I am including the functions file wrong?</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>After hours of messing around and reading more about mysqli etc. I realized that the only problem I actually had was that the script had no idea what <code>$currentUsername</code> was because it was a <a href="http://php.net/manual/en/language.variables.scope.php" rel="nofollow">global variable</a> and functions are not including them automatically in php.</p>
  
  <p>So the error could have been fixed easily by putting <code>global $currentUsername;</code> inside the function <code>nos_check()</code></p>
  
  <p>Below is a rewritten and hopefully better looking code as well:</p>
  
  <pre><code>function nos_check() {
      require 'config.php';
      $con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
      global $currentUsername;
      $query = "SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ";
      $result = mysqli_query($con, $query);
      $row = mysqli_fetch_array($result, MYSQLI_NUM);
      mysqli_free_result($result);
      mysqli_close($con);
  
      if ($row[0] == 0) {
          echo 'You have no sites yet';
          } else {
              echo 'You have more than one site';
              }
      }
  </code></pre>