You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP PDO出现1040 Too Many Connections异常求助(附代码)

Fixing the 1040 Too Many Connections PDO Exception

Hey there, let’s break down why you’re hitting the 1040 Too Many Connections error with your Database.php class, and how to fix it.

First, here’s your code formatted for clarity:

class Database extends \PDO { 
    public function __construct($dsn, $usr = null, $pwd = null, array $options = array()) { 
        $options = $options + $this->getDefaultOptions(); 
        @parent::__construct($dsn, $usr, $pwd, $options); 
    } 

    protected function getDefaultOptions() { 
        return array( 
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, 
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, 
            \PDO::ATTR_EMULATE_PREPARES => false, 
            \PDO::ATTR_STATEMENT_CLASS => array('Slim\PDO\Statement', array($this)), 
        ); 
    } 

    /**
     * @param array $columns
     *
     * @return SelectStatement
     */
    public function select(array $columns = array('*')) { 
        return new SelectStatement($this, $columns); 
    } 

    /**
     * @param array $columnsOrPairs
     *
     * @return InsertStatement
     */
    public function insert(array $columnsOrPairs = array()) { 
        return new InsertStatement($this, $columnsOrPairs); 
    } 

    /**
     * @param array $pairs
     *
     * @return UpdateStatement
     */
    public function update(array $pairs = array()) { 
        return new UpdateStatement($this, $pairs); 
    } 

    /**
     * @param null $table
     *
     * @return DeleteStatement
     */
    public function delete($table = null) { 
        return new DeleteStatement($this, $table); 
    } 
} 

mysqli_close(); 

Key Issues & Fixes

  1. Remove the misplaced mysqli_close(); call
    That line at the end is totally irrelevant here—you’re using PDO, not MySQLi. This function doesn’t affect your PDO connections at all, and it’s probably throwing an unseen warning (since you aren’t passing a valid MySQLi link resource). Delete this line right away.

  2. Stop creating unnecessary connections
    The most common cause of Too Many Connections is spawning a new database connection on every request (or even multiple times per request) instead of reusing a single instance. Your current class doesn’t enforce connection reuse, so every new Database() call opens a fresh connection.

    Implement a singleton pattern to ensure only one connection exists per request:

    class Database extends \PDO {
        private static $instance = null;
    
        public static function getInstance($dsn, $usr = null, $pwd = null, array $options = array()) {
            if (self::$instance === null) {
                self::$instance = new self($dsn, $usr, $pwd, $options);
            }
            return self::$instance;
        }
    
        // Keep the rest of your class code the same...
    }
    
    // Usage example:
    $db = Database::getInstance($yourDsn, $yourUser, $yourPass);
    
  3. Manage connection cleanup
    PHP auto-closes PDO connections when scripts finish, but for long-running apps (like daemons) or if you use persistent connections, manually destroy instances when done:

    $db = null; // Destroys the PDO object and closes the connection
    

    Also, avoid enabling PDO::ATTR_PERSISTENT => true unless you’re confident you can manage persistent connections properly—they can pile up over time.

  4. Adjust database server limits
    If you’ve fixed connection management and still hit the error, your database’s max_connections setting might be too low.

    • For MySQL, check the current value with this query:
      SHOW VARIABLES LIKE 'max_connections';
      
    • If you control the server, edit my.cnf/my.ini to increase the limit (e.g., max_connections = 200). If you’re on shared hosting, reach out to your provider to adjust this for you.

Final Tip

For larger apps, consider using a dependency injection container to manage your database instance instead of a singleton—it’s more flexible and testable. But the singleton pattern is a quick, effective fix for connection bloat.

内容的提问来源于stack exchange,提问作者Ahmed Shahryar Shery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:56:30