title: Why does not my connection to my database inside a function work even after I've connected above?
body: <p>Why does not my connection to my database work even after I've connected?</p>
  
  <p>This is the file I store my connection in: <code>dbase.php</code></p>
  
  <pre><code>&lt;?php
  function connect()
  {
      try
      {   
          $conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'',DB_USER,DB_PASSWORD);
          $conn -&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  
      }catch(PDOException $e) 
      {
          echo 'Error in reaching database: '.$e-&gt;getMessage();
          #Send an email to the admin
          #Display the error page
          die();
      }
          return $conn;
  }
  ?&gt;
  </code></pre>
  
  <p>Then comes this page: <code>index.php</code> : where I include the above file.</p>
  
  <pre><code>&lt;?php
  include_once ($_SERVER['DOCUMENT_ROOT'].'\attach\dbase.php');
  
  $conn = connect();
  
  $what = 1;
  
  $stmt = $conn-&gt;prepare("select id as id, name as name, description as description, level as level from products where level = :what and country = 'US'");
  $stmt-&gt;bindParam(':what', $what);
  $stmt-&gt;execute();
  
  $rows = $stmt-&gt;rowCount();
  
  while($row = $stmt-&gt;fetch())
  {  
      echo $row['name']." ".$row['id'];
      echo "&lt;br&gt;&lt;br&gt;";
  
      fetchElements($row['level'],$row['id']);
  }
  
  function fetchElements($one,$two)
  {   
      //This is line 25
      $elements = $conn-&gt;prepare("select id as id, level as level, name as name, description as description from products where level &gt; :what and parent = :parent and country = 'US'");
      $elements-&gt;bindParam(':what', $one);
      $elements-&gt;bindParam(':parent', $two);
      $elements-&gt;execute();
          //Sql for 3 need to be different
      while($row = $elements-&gt;fetch())
      {  
          echo $row['name']." Id: ".$row['id']." Level: ".$row['level']."&lt;br&gt;";
          if($one != 3)
          {
              fetchElements($row['level'],$row['id']);
          }
      }
      echo "&lt;br&gt;";
  }
  ?&gt;
  </code></pre>
  
  <p>Even when I've connected to the dbase in this page above, when the script calls the function, I get: <code>Notice: Undefined variable: conn in C:\web\apache\htdocs\index.php on line 25 Fatal error: Call to a member function prepare() on a non-object in C:\web\apache\htdocs\index.php on line 25. I've marked line 25 in the file.</code></p>
  
  <p>Why is this happending, and how do I solve this?`</p>