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

Recommended Answers

All 4 Replies

Can I see your code?

//config.php
$dbc = new mysqli(_HOST,_USER,_PASS,_DBNAME);

then

//index.php
	if(!$dbc){
	echo "WHAT";
	}else{
	echo $dbc->get_client_info();
	}

The above outputs my sql version

If I then have another class called user

class user{
public function  __construct($id){
	if(!$dbc){
	echo "WHAT";
	}else{
	echo $dbc->get_client_info();
	}
}
}

and I then create a new user object on the index.php

i receive a "Notice: Undefined variable dbc" error msg

Do I need to pass $dbc into the constructor of user? I'd ideally like to not have to pass that through to every class I create and use the same $dbc object. Similarly to if I had the class orginally and just used mysql_connect I could call any number of mysql queries without a reference to the connection as it was persistent(not sure if that's the correct term)

Yes you will have to pass it to every class. You can use global but its not recommended.

If you really want the best solution, look into the singleton method. Its what I have been using for a while now and it has saved me so much development time.

I think you are not good with PHP. Read php5 books. Don't say which one - every book you get first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.