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

MAKE 同じファイルで Saperate 接続を作成し、それに応じて閉じます。

/ * **** portal1 の接続** * *** /

$portal1_link = mysql_connect('localhost','root','') または die('DB に接続できません'); mysql_select_db('mylekha_auction',$portal1_link) or die('DBを選択できません');

/ * **** portal2 の接続** * *** /

$portal2_link = mysql_connect('localhost','root','') または die('DB に接続できません'); mysql_select_db('mylekha_auction',$portal2_link) or die('DBを選択できません');

于 2012-10-17T09:53:49.527 に答える