0

I have a separate file with an instantiated mysqli object which is in the a folder called includes within the root called connect.php:

$db = new mysqli($host, $user, $password, $dbname);

if ($db -> connect_errno) {
    echo $db -> connect_error;
}

My first page has a require and uses the object $db to carry out a real_escape_string task which works well. I have a functions.php in the includes folder also. Within that there is a function called sendToDB that uses the query function. The functions.php includes the the require function also. However, I get message:

Fatal error: Call to a member function query() on a non-object...

If I instantiate the object within the function sendToDB it successfully writes to the DB. As soon as I take it out, I receive the same message. Is this a global issue? or am I best instantiating it everywhere I need it? Also if using $db on multiple pages, is it safe to run $db->close(); after finishing with it on each page?

user1574598
  • 3,771
  • 7
  • 44
  • 67

1 Answers1

1

At the beginning of the functions that use the database object (e.g. sendToDB), make sure you've got the line :

global $db;

It is ususally required in order to use global variables inside functions.

Maxime
  • 388
  • 3
  • 10
  • Good stuff :-) works a treat. I didn't think it about it being `global` due to it being `required`. Is it best to have `required` or `required_once` like my `functions.php` file is within the other php pages. Its just I read that php does not like functions being declared more than once. – user1574598 Nov 08 '14 at 21:18
  • Check that link: http://stackoverflow.com/questions/2418473/when-should-i-use-require-once-vs-include Basically, as soon as you've got functions in the file, you should perform a require_once. If it answered your question, please mark my answer as accepted :) – Maxime Nov 08 '14 at 21:22
  • Thanks again - yes I tried to mark you correct instantly, but it told me I had to wait for a few mins. – user1574598 Nov 08 '14 at 21:28
  • Just another question if ok - I did mention it above. Now I have everything working, is it okay or best practice to perform `$db -> close()` at the end of each page? I have tried it and it seems to be ok so far. The object must re-instantiate itself when it sees its needed if and when on each page? – user1574598 Nov 08 '14 at 21:53
  • Yes, performing a $db->close() at the very end of your script is the way to go! – Maxime Nov 08 '14 at 22:17