0

关于使用数据库连接在 PHP 中编程时什么是最好的,我有一个一般性的问题。我正在构建一个包含多个模块的项目,每个模块有时都需要连接到 MySQL。根据用户从菜单中选择的操作,模块文件包含在主 index.php 中。我想,无论如何,大多数项目都是这样工作的。

到目前为止,我所做的总是在每个模块文件的开头打开连接,并在查询运行后关闭它。

我的问题是:最好在 index.php 的开头打开与数据库的连接并在最后关闭它以便打开 1 个连接,还是做多个保持打开时间更短的连接?什么最适合速度和开销?

4

2 回答 2

1

正如 NB 所指出的,您可能应该设置一个类来处理所有与数据库相关的任务。我从我的代码档案中发布了一个片段来说明如何设置这样的类。这仅用于说明目的,如果您只是复制和粘贴,则不保证对您有用。它可能需要一些改进。它还利用 smarty 类来处理数据视图。

我建议去掉你不需要的东西。设置您的 MySQL 连接参数。在您的索引文件中,您可以实例化一个 SQL 对象并简单地调用适当的方法。这些方法返回并将结果保存为关联数组和索引数组。遍历表行很简单:

$SQL->GetRows('RowTemplate.tpl', 'StoredProcedure', 'Parameters');

仅供参考,这是更大的 $Portal 框架对象的一部分,以防您想知道 $Portal 引用是什么。$SQL 只是扩展了 $Portal。

我希望这有帮助。祝你好运

class SQL {
        /********** MEMBER VARIABLES **********************************************************************/
        var $Connection;                // DB connection handler
        var $Result;                    // ResultSet returned from last call during life of object instance
        var $RowCount;                  // RowCount for ResultSet returned from last call during life of object instance
        var $ResultArray;               // ResultSet Array returned from last call during life of object instance
        var $Query;                     // Query last submitted during life of object instance
        var $ErrorNumber;               // Error number for error returned from last call during life of object instance
        var $Error;                     // Error returned from last call during life of object instance
        var $Message;                   // Messages returned during life of object instance

        // Switches, flags, markers, etc
        var $DebugMode;
        var $LogActive;
        var $ShowErrorMsg;

        // Modules array
        var $Modules;

        // SQL Connection Info - PROTECTED!
        protected $Host = "localhost";
        protected $User = "mydatabase";
        protected $Password = "mypassword";
        protected $Schema = "myschema";


        /********** MEMBER FUNCTIONS **********************************************************************/
        // Object Constructor
        function __construct() {
            // Automatically open DB Connection
            //$this->OpenDBConnection();
            //echo "User Object Constructor<br>";
        }

        // Open new DB Connection
        function OpenDBConnection() {
            return ($this->Connection = mysqli_connect($this->Host, $this->User, $this->Password, $this->Schema))? true : false;
        }

        // Close DB Connection
        function CloseDBConnection() {
            mysqli_close($this->Connection);
            //return true;
        }

        // Return error messages
        function GetError() {
            return $this->Error;
        }

        // Return last query string
        function GetQuery() {
            return $this->Query;
        }


        // Call, execute stored procedure and return result set
        /*  NOTES:  The result set is always returned as an int array of associative arrays
                    That is, if $Result was returned, the first row would be referenced as $Result[0]
                    and any column of the first row would be referenced as $Result[0]['ColumnName'] 

            COMMENTS: */

        function CallProcedure($StoredProcedure) {
            // Clear any System Errors
            $this->ErrorNumber = '';
            $this->Error = '';

            // Open DB Connection
            if(!$this->OpenDBConnection()) return false;

            // Kill error if there are no extra Params passed
            $Params = @func_get_arg(1);

            // Build Query
            $this->Query = "CALL $StoredProcedure ($Params)";

            //if($this->Result = $this->Connection->query($this->Query)) {
            if($this->Result = mysqli_query($this->Connection, $this->Query)) {
                // Reset global Result Set
                $this->ResultArray = Array();

                // Set record count for current record set
                $this->RowCount = 0;

                while($Row = @mysqli_fetch_array($this->Result, MYSQLI_BOTH)) {
                    $this->ResultArray[$this->RowCount] = $Row;
                    $this->RowCount++;
                }

                // Close DB Connection
                $this->CloseDBConnection();

                return $this->ResultArray;
            }

            // Grab Error
            $this->ErrorNumber = mysqli_errno($this->Connection);
            $this->Error = mysqli_error($this->Connection);


            // Close DB Connection
            $this->CloseDBConnection();
            return false;
        }


        /* Using Smarty class, return row template filled with record set from given stored procedure
                EXAMPLE 1: Primary Function - Using data set from stored procedure
                            $Portal->SQL->GetRows('RowTemplate.tpl', 'StoredProcedure', 'Parameters');
                EXAMPLE 2: Secondary Function - Using data set in second dimensional associative array
                            $Portal->SQL->GetRows('RowTemplate.tpl', 'ARRAY', $MyDataSetArray); */
        function GetRows($RowTemplate, $Procedure) {
            // Kill error if there are no extra Params passed
            $Parameters = @func_get_arg(2);
            // Set return string
            $ReturnString = '';
            // If Procedure is ARRAY then params are data set else Call procedure and return results array 
            $Result = ($Procedure=='ARRAY')? $Parameters : $this->CallProcedure($Procedure, $Parameters);

            // Loop through result set initializing smarty obj for each row
            $Count = 0;
            while(IsSet($Result[$Count])) {
                $RowTemplateObj = new Smarty;
                $RowTemplateObj->assign('SCRIPT_NAME', SCRIPT_NAME);
                $RowTemplateObj->assign('HOST_NAME', HOST_NAME);

                // Loop though each result row as an associative array of column - values 
                foreach ($Result[$Count] as $Key => $Value) {
                    if(IsSet($Result[$Count][$Key])) $RowTemplateObj->assign($Key, (is_array($Value))?$Value:stripslashes($Value));
                    //if(IsSet($Result[$Count][$Key])) $RowTemplateObj->assign($Key, $Value);
                }

                $RowTemplateObj->assign('bgcolor', '{$bgcolor'. ($Count%2 + 1) .'}');

                // Concatenate populated row into return string
                $ReturnString .= $RowTemplateObj->fetch($RowTemplate);
                $Count++;
            }

            return $ReturnString;
        }


        function GetSelectList($Procedure, $Parameters, $OptionValueField, $OptionNameField) {
            // Kill error if there are no extra Params passed
            $Selected = @func_get_arg(4);
            // Set return string
            $ReturnString = '';
            // Get List Resultset
            $Result = $this->CallProcedure($Procedure, $Parameters);

            // Loop through result set and set <option> ta row
            $Count = 0;
            while(IsSet($Result[$Count])) {
                $ReturnString .= '<option value="'.$Result[$Count][$OptionValueField].'"';
                $ReturnString .= ($Selected==$Result[$Count][$OptionValueField])? ' selected ' : '';
                $ReturnString .= '>'.$Result[$Count][$OptionNameField].'</option>';
                $Count++;
            }

            return $ReturnString;
        }


        function Execute($SQL) {
            // Clear any System Errors
            $this->ErrorNumber = '';
            $this->Error = '';

            // Open DB Connection
            if(!$this->OpenDBConnection()) return false;

            // Assign Query
            $this->Query = $SQL;

            if($this->Result = mysqli_query($this->Connection, $this->Query)) {
                // Reset global Result Set
                $this->ResultArray = Array();

                // Set record count for current record set
                $this->RowCount = 0;

                while($Row = @mysqli_fetch_array($this->Result, MYSQLI_BOTH)) {
                    $this->ResultArray[$this->RowCount] = $Row;
                    $this->RowCount++;
                }

                // Close DB Connection
                $this->CloseDBConnection();

                return $this->ResultArray;
            }

            // Grab Error
            $this->ErrorNumber = mysqli_errno($this->Connection);
            $this->Error = mysqli_error($this->Connection);

            // Close DB Connection
            $this->CloseDBConnection();
            return false;
        }
于 2012-10-19T17:33:20.277 回答
-3

在同一个文件中建立单独的连接并根据它们关闭它们。

/ * ****门户1的连接** * *** /

$portal1_link = mysql_connect('localhost','root','') or die('无法连接到数据库'); mysql_select_db('mylekha_auction',$portal1_link) or die('无法选择数据库');

/ * ****门户2的连接** * *** /

$portal2_link = mysql_connect('localhost','root','') or die('无法连接到数据库'); mysql_select_db('mylekha_auction',$portal2_link) or die('无法选择数据库');

于 2012-10-17T09:53:49.527 回答