tags:

views:

49

answers:

3

I wrote this code

require('Database.class.php');



     function get_info (){



     $db = new Database($config['server'], $config['user'], $config['pass'], $config['database'], $config['tablePrefix']);
     $db->connect();


     $sql = $db->query('SELECT * FROM ja_cat');
     while ($options = $db->fetch_array($sql)) {

      $cat[].=" ".$options['title'];
     }
     $db->close();
     return $cat;

then I get this Mysql error

Mysql Error : No database selected .

but when I put the require instruction inside the function it's work fine

+4  A: 

My guess is Database.class.php creates some variables that are probably global in scope that it relies upon. If you require it inside the function and it works, that supports that theory. Is that your class? Can you change it? Can you post it?

Basically $config needs a global qualifier inside the function.

cletus
Why the downvotes? This is correct.
Ionuț G. Stan
here it is http://www.ricocheting.com/scripts/php_mysql_wrapper.php , Andrew solved the problem
Waseem
Ya he wrote out the reason and I wrote out the fix, I suppose I should have elaborated as to the WHY behind my HOW.
Andrew G. Johnson
+3  A: 

Make this the first line IN your get_info() function:

global $config;

Also, you may want to define $db outside of the function at the start of the code and then close the connection at the end, instead of having to re-connect multiple times.

Andrew G. Johnson
+2  A: 

You have to import the global variable $config into the scope of the function:

function get_info() {
    global $config;
}
Ionuț G. Stan
You guys just don't see the problem? Isn't it?
Ionuț G. Stan
why is this downvoted?
Tom Haigh