讓我們創建一個很簡單的例子文件:我是否需要在每個定義的函數中建立另一個數據庫連接?
index.php
:
<?php
$connection = mysqli_connect('localhost', 'user', 'pass', 'db');
// connection established successfully
echo 'doing something here for like 500 lines of code';
include('functions.php');
echo countCTR(12, 15);
?>
現在的問題是functions.php
:
<?php
function countCTR($input1, $input2){
/* in this function I need my database connection ($connection)
which was established already in index.php before this
file was included. however, the $connection isn't open
inside this function. Do I have to execute mysqli_connect
inside every function I define?
*/
}
?>
將該連接作爲函數的附加參數傳遞 – 2012-02-24 11:16:08
@MarkBaker:我相信我已經嘗試過了,它不起作用。 – 2012-02-24 11:24:04
您必須檢查$ connection是否爲NULL,如果是,則必須在每個方法內調用mysql_connect()。這就是爲什麼我建議使用mysql_pconnect()調用 - 所以你不必做檢查......正如我在下面寫的,如果存在,mysql_pconnect()將重新使用你先前建立的連接,如果不存在,它將使另一個。 – DejanLekic 2012-02-24 11:26:45