Maintain $dbh (database handle) across all php fil

2020-05-06 09:10发布

问题:

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

回答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.



标签: pdo