我怎样才能防止多次连接到数据库

时间:2013-10-10 03:57:34

标签: php mysql database pdo global-variables

这是我的代码

pdo.php

class Connection {  
   public function __construct() {  
      $this->connect ($db);  
   }  
private function connect($db) {  
    try {  
        if (! $db){  
                  $this->db = new PDO ( 'mysql:host=localhost;dbname=Shopping;charset=utf8', 'xxxx', 'xxxxx' );  
                  echo 'Connected';  
                  return $this->db;  
        }  
        catch ( PDOException $conError ) {  
        echo 'failed to connect DB' . $conError->getMessage ();  
    }  
 }  
}

product.php

class ProductInsert extends Connection {  //here my function is called multiple times 
    function __construct() {  
         parent::__construct($db);  
    }    
    public function prdInsert(.....)  
    {  ........}

这里我的问题是多次打开数据库连接。当我调用productInsert()时,然后打开数据库连接,我怎么能阻止这个

3 个答案:

答案 0 :(得分:1)

不要从数据库类扩展应用程序类。

这是你的主要问题 它们是完全不同的类,没有任何共同之处 因此,您必须将您的db对象用作属性

连接类目前也没用,因为它只是PDO的漏洞伪装。

因此,只需创建原始PDO对象,然后将其传递给产品的构造函数

class ProductInsert
{
    function __construct(PDO $db)
    {  
        $this->db = $db;  
    }    
    public function prdInsert(.....)  
}

为了善良,学会缩进代码。

答案 1 :(得分:0)

 class Connection {  
        public function __construct($db) {  
        return $this->connect($db);  
        }  
        private function connect($db) {  
        try {  
        if (! $db){  
        $db = new PDO ( 'mysql:host=localhost;dbname=Shopping;charset=utf8', 'xxxx', 'xxxxx' );  
        echo 'new connection';  
        }
        return $db;  
        }  
        catch ( PDOException $conError ) {  
        echo 'failed to connect DB' . $conError->getMessage ();  
        }    

        }
}

答案 2 :(得分:0)

这是解决方案
pdo.php

class Connection {
// Declare instance  
private static $instance = NULL;  
// the constructor is set to private so so nobody can create a new instance using new
private function __construct() {
// maybe set the db name here later 
}
// Return DB instance or create intitial connection @return object (PDO) @access public
public static function getInstance() {
    if (! self::$instance) {
        self::$instance = new PDO ( 'mysql:host=localhost;dbname=Shopping;charset=utf8', 'root', 'vss0ftech' );
        self::$instance->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        echo 'connected';
    } else
        echo 'connection is already existed';
    return self::$instance;     
}
// Like the constructor, we make __clone private so nobody can clone the instance
PRIVATE FUNCTION __CLONE() {
}
}

<强> product.php

这里我们可以像这样调用方法

class ProductInsert {  
    public function prdInsert(.....) {  
        $result_By_Vendor_And_Title = Connection::getInstance ()->query ( "select * from........)  
     }  
  }