title: "Notice: Undefined variable" but variable is declared in a function
body: <p>I am going though my site and trying to make it more future proof and cleaner so converting a lot of things to common functions.</p>
  
  <p>I have a particular function that takes the the users session (session name is the username) and it runs a query on the database which fetches all of the other data for that user.</p>
  
  <p>I wish to use the <code>userID</code> in some parts but i am getting the error "Notice: Undefined variable"</p>
  
  <p>This is an example:</p>
  
  <pre><code>function getUserData_FromSession() {
  if (isset($_SESSION['user'])) {
  
      $username = "root"; 
      $password = "root"; 
      $host = "localhost"; 
      $dbname = "06vids";
  
      $options = array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8'); 
      try 
      { 
      $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
      } 
      catch(PDOException $ex) 
      { 
      die("Failed to connect to the database: " . $ex-&gt;getMessage()); 
      } 
      $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
      $db-&gt;setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
  
      $stmt = $db-&gt;prepare('SELECT * FROM users WHERE username = "' . $_SESSION['user']. '"');
      $stmt-&gt;execute();
      $stmt-&gt;setFetchMode(PDO::FETCH_ASSOC);
      while($row = $stmt-&gt;fetch()){
      $userid = $row['id'];
      $usernameuser = $row['username'];
      }
  
  }
   }
  </code></pre>
  
  <p>That function is in a functions file that is included in a page, on that page i do this:</p>
  
  <pre><code> getUserData_FromSession();
  
   if ($userid == $userbuildid) {
      $editenabled = 'edity';
  } else if ($userid !== $userbuildid) {
      $editenabled = 'editx';
  }
  </code></pre>
  
  <p>This gives the error that $userid is undeclared. If i have the query actually on the same page then it works fine, but i dont want to have loads of querys popping up everywhere.</p>