0

How many ways are there to maintain $dbh (database handle) across all php files, so that once $dbh created, I can query and update database from any php file and any time, without having to log in.

1) apply $dbh global in every php file ? 2) apply $dbh in the parameter of the called function ? 3) ?

What other ways are there to, so as to query and update without ever having to log in again and which is better and simple.

Thanks for your input.

regards Clement

user1739825
  • 820
  • 4
  • 10
  • 27

1 Answers1

-1

In the file that creates $dbh, put

global $dbh;
...
$dbh = new DatabaseClass();
$dbh->example_login("user","pass");
...

In every file and function that wants to use $dbh, put

global $dbh;
...
$result = $dbh->query("SELECT * FROM XYZ");
...

at the start to mark $dbh as global. You could also use a singleton type pattern, although this is considered bad practice in PHP.

AStupidNoob
  • 1,980
  • 3
  • 23
  • 35
  • Using global $dbh is a good idea? What other methods are there? – user1739825 Jul 23 '13 at 03:02
  • @user1739825 AFAIK, it is the best thing you can do. I've seen it used extensively for the database handle and some other things in phpBB for example, so it seems like the way to go. As I said, you could always put it in a static variable of a class, kinda like a singleton, but I'd say `global` is the way to go here. – AStupidNoob Jul 23 '13 at 03:57
  • To AStupidNoob, I could not resolve the problem. Pls refer to [problem] (http://stackoverflow.com/questions/17806637/make-dbh1database-handle-availabel-to-all-php-files). – user1739825 Jul 23 '13 at 09:49
  • I've added a comment there, hopefully it will help you. You should probably accept this answer as correct or answer your own question to show that it doesn't need attention. – AStupidNoob Jul 23 '13 at 10:16