0

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

here it is ricocheting.com/scripts/php_mysql_wrapper.php , Andrew solved the problem
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.
3

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.

Comments

2

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

function get_info() {
    global $config;
}

1 Comment

You guys just don't see the problem? Isn't it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.