2014-09-04 33 views
0

我有一個功能我可以使用函數作爲mysql_close(function)的參數;

function connect 
{ 
$c = MySQL_connect('db','ss','nn'); 
if(!$c) 
die(); 
} 

現在我可以用 MySQL_close(連接()); 關閉連接,因爲我必須在一個函數和許多數據庫中使用很多連接。

+0

'mysql_query'和相關功能已經過時接口,不應在新的應用中使用,並將在PHP的未來版本中刪除。像[PDO這樣的現代化替代品並不難學](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/)。如果您是PHP的新手,像[PHP The Right Way](http://www.phptherightway.com/)這樣的指南可以幫助解釋最佳做法。 – tadman 2014-09-04 17:14:49

回答

0

你可以這樣做:

$conn1 = mysql_connect(...); 
$conn2 = mysql_connect(...); 

// any code here... 

mysql_close($conn1); 
mysql_close($conn2); 

你使用PHP? Mysql _...函數在PHP中不推薦使用。改用Mysqli或PDO。 Mysqli有一個非常類似於舊的Mysql擴展的API。

最新通報

評論:我會寫的,而不是 'mysql的' mysqli的「。我的例子是簡單的程序風格。

  • 函數也可以返回一個連接。
  • 如果您使用多個數據庫,那麼您可以在以下之間切換:mysqli_db_select("other_db");
  • 如果使用-模式間的查詢,然後使用完全前綴的表名是一個更好的選擇:mysqli_query("SELECT * FROM db1.users UNION SELECT * FROM db2.users");
  • 最好的選擇是基於配置連接處理。將配置文件中的連接設置映射(或PDO和許多DBAL庫支持的dsn -s)置入並在創建時加載。這是一個簡單的例子:

    function loadDbConfiguration($name) { 
        $configs = yaml_parse(...); 
        if (array_key_exists($name, $configs)) { 
         return $configs[$name]; 
        } else { 
         // throw any exception or do something other what you prefer 
        } 
    } 
    
    function getConnection($name) { 
        static $connections; 
        if (is_null($connections)) { 
         $connections = array(); 
        } 
    
        if (array_key_exists($name, $connections)) { 
         return $connections[$name]; 
        } 
    
        $config = loadDbConfiguration($name); 
        if (([email protected]_connect( [use $config here...] ))!==false) { 
         $connections[$name] = $conn; 
         return $conn; 
        } else { 
         // throw any exception or do something other what you prefer 
        } 
    } 
    
    function closeConnection($name) { 
        // do not forget to add error handlings 
        mysqli_close(getConnection($name)); 
    } 
    
    $defaultConn = getConnection("default"); 
    $site1Conn = getConnection("site1"); 
    
    // any code here... 
    
    // later... 
    $myDefaultConn = getConnection("default"); // will same as $defaultConn 
    $site2Conn = getConnection("site2"); 
    
    // at end: 
    closeConnection("default"); 
    closeConnection("site1"); 
    closeConnection("site2"); 
    

    `

+0

thx for rply但是,m使用函數進行連接,在單個頁面中,我需要多次使用diffrnt連接,所以方法是,如果對函數connect()所做的任何更改都將適用於所有。而已。 – 2014-09-05 03:57:47

+0

查看我的更新。 – 2014-09-05 12:55:42

相關問題