PHP Function Accessing Database Connection

前端 未结 5 554
走了就别回头了
走了就别回头了 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:59

    its so simple just pass your $conn variable into another calling function(instead of making new connection) like

    yourpage.php

    $conn = new mysqli($servername, $username, $password, $dbname);
    someFunction ($conn)//you can add other parameters if you like 
    
    function someFunction ($conn) {
        $result = mysqli_query ($conn, "SELECT * FROM examples);
    }
    

    Note:This is not good practice to always make new connection for database access.so always make connection once and use it every where.(but if your requirement different and require multiples connections then you can make multiples connections)

提交回复
热议问题