-1

I have a simple mysqli wrapper class I use for my database operations. I am defining (instantiating?) that class at the top of the code presumably where it should be globally accessable, however when I try to use this reference to the db class within a recursive function, xdebug tells me it is out of scope - so as a fix I have had to define the database twice, but this seems like poor practice. Can anyone tell whats up or where I'm going wrong?

The code is recursively printing nested comments from the database FYI.

The code is as follows...

<?php
require 'lib/mysqli.class.php';  // the pretty standard mysqli class
$config = array();$config['host'] = 'localhost';$config['user'] = 'root';$config['pass'] = '';$config['table'] = 'publicate';

$db = new DB($config);     // new instance of database
//$db->setFetchMode(2);      // fetch data by association (MYSQLI_ASSOC)

// Run a Query:
$db->query('SELECT * FROM comments WHERE parentid = 0');        

// Get the data:
$root_sql = $db->get();

recursive_categories($root_sql);

function recursive_categories($results)
{
     if(count($results))
     {
         echo "<ul>";
         foreach($results as $res)
         {
             echo "<li>" . "id=" . $res['id'] . ", pid=" . $res['parentid'] . ", content: " . $res['content'];


             //Rest of what ever you want to do with each row

             //Check this category for children ************************
             //2nd definition of DB ************************
             $config = array();$config['host'] = 'localhost';$config['user'] = 'root';$config['pass'] = '';$config['table'] = 'publicate';
             $db2 = new DB($config);     // new instance of database
             $db2->query("SELECT * FROM comments WHERE parentid  = " . $res['id']);
             $rows = $db2->get();

             recursive_categories($rows);

             //has to be after the inner loops
             echo "</li>";
         }
         echo "</ul>";
     }
}
?>

Thanks.

hakre
  • 178,314
  • 47
  • 389
  • 754
Gga
  • 3,935
  • 12
  • 36
  • 73
  • possible duplicate of [Variable Scope and Functions](http://stackoverflow.com/questions/4022536/variable-scope-and-functions), [Can't access global variable inside function](http://stackoverflow.com/questions/5449526/) – outis Jan 14 '12 at 12:34

1 Answers1

1

You need to pass your $db connection to the function like so:

function recursive_categories($results, $db)

Then it will be available inside the function variable scope.

Another issue that comes to mind ... If this file resides inside a publicly accessible web directory you definitely don't want to have your actual database credentials just chilling there out in the open.

rdlowrey
  • 37,397
  • 9
  • 74
  • 98
  • Thanks, that was it, very much appreciated. Apologies for the novice Q too by the way. This is just for testing purposes in regards to the db credentials. – Gga Dec 02 '11 at 16:56