简体   繁体   中英

PHP Mysqli database connection pooling to avoid maximum user count

I surfed on Internet for past two days to create the DB pooling by PHP, but not yet achieved. I'm using PHP and MySQLi. We bought the mysqli db with 15 Maximum user connection. I want to pool the db connection to avoid the new connection. I used persistent as well as mysqli_connect . but I don't feel much different both are creating the new connection since other user already logged in. I was trying this function to get DB connection.

 <?php
function getConnection(){
    if ($connect){
        return $connect;
    }else{
        $connect = new mysqli('p:xxxx','yyy','zzz','aaaa');
        return $connect;
        if(mysqli_connect_errno($connect))
        {
            echo "Server Busy";
        }
    }
}
 ?>

But above function only returns the else part. Please suggest me how to handle this. Thanks in advance. For now I'm killing the process which are in sleep mode to reduce the probability of increasing DB connection.

There is no connection pooling in PHP.

The persistent connection you are trying to use (that "p:" bit) is the most sure way to hit the maximum connection number, so get rid of it immediately.

15 concurrent connections is, actually, A LOT. Simply optimize your queries, so a typical connection would last 0.1 second, which would mean 150 concurrently executed PHP scripts which is like 1500 users on-line.

Also, you need to add

static $connect;

as the first line in your function, or is will create the new connection every time it is called, which is the actual reason why you are getting this error.

<?php
function getConnection(){
    static $connect;

    if (!$connect){
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $connect = new mysqli('xxxx','yyy','zzz','aaaa');
        $connect->set_charset('utf8mb4');
    }
    return $connect;
}

Better yet, get rid of this function at all, have a separate file with the mysql connection code, and then use the $connect variable all around your code. See my article about mysqli connect for the details.

This is not how it works. See here . MySQLi will select one of available connections when you execute new mysqli('p:... The connection is persistent, not the PHP object.

function getConnection(){
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    return (new mysqli('p:xxxx','yyy','zzz','aaaa'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM