Forum Moderators: coopster

Message Too Old, No Replies

mysqli instance and variable not declared

         

Tommybs

10:12 am on Jun 20, 2009 (gmt 0)

10+ Year Member



Hi all,

I've recently begun working with mysqli in a php site in order to make use of bound queries.

Now I have a config file that I am including in all pages that has something similar to:


$dbc = new mysqli(_HOST,_USER,_PASS,_DBNAME);

and this works as expected. If I then execute a query on a page (say index.php) it works as expected.

If I then have a class that is included on the page AFTER the config script and I want to do some DB stuff in that class I get an undefined variable message (when using $dbc as the variable)

Am I doing something really stupid here? Does the $dbc need to be passed into the class? How can I set it so that I have my $dbc object and I can access it within other classes?

Many Thanks

coopster

12:16 pm on Jun 20, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You are running into a variable scope [php.net] issue. Your database connection resource (variable) is in the global scope but your class does not have direct access to that variable like it does to the superglobals [php.net].

Since you are familiar with classes, I would highly recommend considering a singleton instance of the database. There is an example on this page:
[webmasterworld.com...]
to help you get rolling. Incorporate that with your mysqli methods and you should be good to go.

Tommybs

12:25 pm on Jun 20, 2009 (gmt 0)

10+ Year Member



Thanks, I will look into that and hopefully achieve what I'm after