How to handle too many database connections in PHP without increasing to maximum connections?

There is a file named function.php, and I call it on all pages of my site using require_once. This file contains over one hundred functions.

I get an error max_user_connectionsfrom mysqli_connect()and right after that

mysqli_query () expects parameter 1 to be mysqli, boolean given

an error is shown when too many visitors or search bots are quickly crawled.

The function file looks like this:

<?php 
function db_connect(){
    $link=mysqli_connect("host","dbuser","dbpass","dbname");
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    mysqli_query($link,"set names 'utf8'");
}

db_connect();

function func_1(){
    $result=mysqli_query($link,"select * from ...");
    ...
}

function func_2(){
    $result=mysqli_query($link,"select * from ...");
    ...
}

.
.
.

function func_100(){
    $result=mysqli_query($link,"select * from ...");
    ...
}
?>

At the end, I close the database connection. Since I checked the maximum connection for each user for my database is 50, and the host provider will not change it (enough, they said).

So, in general, how can I deal with this problem? (simple PHP or OOP)

+4
6

, MySQL -.

db_connect() . , , , . , , .

, , . MySQL , require_once, . , .

, - MySQL, php-, - . , - apache MaxClients / MaxRequestsPerChild. - nginx . , - .

0

, . , . . , , , , , , , 10 . , , , , , , , .

0

. -

, 50, (, ).

, / , /, . 50 , , Wordpress (, 1000 ). . PHP 50 . , .

, , . , , -, .

0

singleton $link function.php.

0

getLink, :

function getLink() {
    static $link;

    if(! $link) 
        $link = db_onnection() ;

    return $link;
} 

:

mysqli_query(getLink(), "SELECT id,...");

, , -!

0

:

-, $link . :

<?php 
$link = null;
function db_connect(){
    global $link;
    $link=mysqli_connect("host","dbuser","dbpass","dbname");
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    mysqli_query($link,"set names 'utf8'");
}

db_connect();

function func_1(){
    global $link;
    $result=mysqli_query($link,"select * from ...");
    ...
}

function func_2(){
    global $link;
    $result=mysqli_query($link,"select * from ...");
    ...
}

.
.
.

function func_100(){
    global $link;
    $result=mysqli_query($link,"select * from ...");
    ...
}
?>

: ( . ). require_once. , , :

if (!$link) db_connect();

( $link, , )

-: PHP , , . , mysqli_close, , . , : http://php.net/manual/en/mysqli.close.php

, , , php . , "p:" ( ). , sql.myserver.com, :

$link=mysqli_connect("p:sql.myserver.com","dbuser","dbpass","dbname");

You can get more information about persistent connections to mysqli in the php manual on this page: http://php.net/manual/en/mysqli.persistconns.php

-1
source

Source: https://habr.com/ru/post/1682608/


All Articles