Maintain $dbh (database handle) across all php files

前端 未结 1 878
忘掉有多难
忘掉有多难 2021-01-26 15:03

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, witho

1条回答
  •  失恋的感觉
    2021-01-26 15:45

    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.

    0 讨论(0)
提交回复
热议问题