PHP Function Accessing Database Connection

前端 未结 5 537
走了就别回头了
走了就别回头了 2021-01-14 09:15

How do I allow a function to access a database connection without using GLOBAL?

config.php

 DEFINE (\'DB_HOSTNAME\', \'hostname\');
 DEFINE (\'DB_DAT         


        
5条回答
  •  耶瑟儿~
    2021-01-14 09:41

    Either pass the database handle to your function, as @KingCrunch and others have said, or call a function that returns the handle:

    In config.php:

    function get_dbc() {
        $dbc = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        if(!$dbc) die("Unable to connect to MySQL: " . mysqli_error($dbc));
        return $dbc;
    }
    

    In functions.php:

    require_once('config.php');
    
    function something()
    {
        $dbc = get_dbc();
        $info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
    }
    

    You may wish to look at The mysqli Extension and Persistent Connections for details on how you can prevent the connection from being re-established on each call to get_dbc(). There are alternative approaches to this, such as creating a singleton class for your database connection.

提交回复
热议问题