/    Sign up×
Community /Pin to ProfileBookmark

Connection Error

Can anyone help me? I’m getting this error frequently. My website is made up of multiple classes with methods which all require a DB query.

when I load a page I get the person as per this example, this includes a database query. when I get specific info like last meetings I get do another query of the database to get this information.

I don’t get this all the time but it pops up for time to time.

im wondering if I’m doing it to myself with too many connections or if there’s a better way to do my connection? Pass it into ever method for example?

currently I create an instance of the Database class and connect to it when I need it.

[code] Warning: mysqli::__construct(): (HY000/1040): Too many connections in /home2/myfolder/my site.com/db.php on line 119

Warning: mysqli::prepare(): Couldn’t fetch mysqli in /home2/myfolder/my site.com/index.php on line 37

Fatal error: Uncaught Error: Call to a member function bind_param() on bool in /home2/myfolder/my site.com/index.php:38 Stack trace: #0 /home2/myfolder/public_html/my site.com/index.php(9): Person->getById(‘368’) #1 {main} thrown in /home2/myfolder/my site.com/index.php on line 38

[/code]

to post a comment
PHP

64 Comments(s)

Copy linkTweet thisAlerts:
@sibertNov 29.2021 — > @kiwis80#1639991 im wondering if I’m doing it to myself with too many connections or if there’s a better way to do my connection?

I am working with Go and Postgresql and there are ways to close connections and set session length so that the database is not being overloaded. Free connections / sessions sort of.
Copy linkTweet thisAlerts:
@kiwisauthorNov 29.2021 — @sibert#1639992

At the end of the page do you call a method forcing the closure of the/any connection?

I could if im not wrong move to. PDO connect. Set a connection and pass it into every method called?

im not sure how that would work from inside the class vs from my public page
Copy linkTweet thisAlerts:
@ginerjmNov 29.2021 — Usually one returns the connection from the connect method and uses that in the rest of the script.
Copy linkTweet thisAlerts:
@SempervivumNov 29.2021 — >if there’s a better way to do my connection?

Recently I recommended using the singleton pattern. This way you could create multiple instances of your class but create only one connection.
Copy linkTweet thisAlerts:
@kiwisauthorNov 29.2021 — @Sempervivum#1639996

I used that suggestion. I’m not sure if it’s possible to test that it’s using a single instance or not??

im still getting this error even after using that suggestion
Copy linkTweet thisAlerts:
@SempervivumNov 29.2021 — @kiwis80#1639998 I see, I was not aware that you were the user in that thread. In this situation I would recommend to do some debugging by adding var_dumps in order to trace the behaviour of that class.
Copy linkTweet thisAlerts:
@kiwisauthorNov 29.2021 — @Sempervivum#1640000

I’ve been playing with this issue for a few months. I’m not sure if we’re talking the same thread. I recall a post of using a database as a singleton so tried to implement it. I’m on a shared server so it could be other users as well.

how would I even go about testing this? What would I be looking for?
Copy linkTweet thisAlerts:
@SempervivumNov 29.2021 — Unfortunately I can't find that thread again. I think it would to best if you post your current code of that database class.
Copy linkTweet thisAlerts:
@NogDogNov 29.2021 — There are multiple ways to skin this cat, but my preferred way is to create one database connection object as part of my start-up or config file, then pass that into any class/function that needs it. With OOP stuff, just make it one of the __construct() parameters, and have that constructor save it a a class property that can be accessed by any method that needs it. (And you can use type-hinting to enforce it.)
[code=php]
class Example {
private $db;
public function __construct(mysqli $db) {
$this->db = $db;
}
public function something() {
// use $this->db when you need the mysqli connection
}
}
[/code]
Copy linkTweet thisAlerts:
@SempervivumNov 29.2021 — @kiwis80#1640004 I found that previous thread:

https://www.webdeveloper.com/d/397339-mysql-error-hy00001040/8

NogDog posted a piece of code either, which one did you use?
Copy linkTweet thisAlerts:
@kiwisauthorNov 30.2021 — @Sempervivum#1640007

I currently have this and I'm not sure how to dump any info around if it's a single instance or where or how my database is overloaded etc

<i>
</i> private function __construct(){
$this-&gt;servername = "localhost";
$this-&gt;charset = "utf8mb4";
$this-&gt;username = "username";
$this-&gt;password = "password";
$this-&gt;dbname = "dbname";
$this-&gt;conn = new mysqli($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
<br/>
<i> </i>}

<i> </i>public static function connect(){
<i> </i>
<i> </i> if (self::$instance == null){
<i> </i> self::$instance = new dbh();
<i> </i> }

<i> </i> return self::$instance;

<i> </i>}

<i> </i>public function getConnection() {
<i> </i> return $this-&gt;conn;
<i> </i>}
<i> </i>


When connecting to it I use this

<i>
</i> $Db = dbh::connect();;
$con = $Db-&gt;getConnection();
Copy linkTweet thisAlerts:
@kiwisauthorNov 30.2021 — @kiwis80#1640009

But in saying this, I've also created a version of NogDog idea, I'm happy to move towards this approach if isolating or minimizing any risk of overloading is improved
Copy linkTweet thisAlerts:
@HyperledgerDevelopmentServicesNov 30.2021 — **Hyperledger** can be better termed as the next level of blockchain. It focuses on improving performance and reliability by the collaboration of developing blockchains and distributed ledgers. With [Hyperledger development ](https://www.nadcab.com/hyperledger-development)becomes highly suitable to businesses like finance, insurance, healthcare, automobile, and supply chain. This particular form of distributed ledger works on user-specific modules, offering services such as storage routines, identity, access control, and smart contracts. There are varieties in Hyperledgers and each one of them serves a specific purpose. This is an upgraded version of distributed ledger which works in better the refinement of resources.
Copy linkTweet thisAlerts:
@kiwisauthorNov 30.2021 — So I played around and tested Nogdogs code yesterday. Below is an example of it.

it works, someone a class creates a list of others classes so within a for each loop of a class I have

<i>
</i>$secondClass = new secondClass($this-&gt;dbh);


so when on my normal page I create an instance of my first class I pass in my database, that passes it over to any new classes created within it.

I need to do a lot of rework to move my current stuff over to this.

how likely will this improve things and how can I troubleshoot this if the error continues to occur?

example code
<i>
</i>class dbh extends mysqli {
private $servername = "localhost";
private $username = "ABC";
private $password = "ABC";
private $dbname = "ABC";
public function __construct() {
// call the actual mysqli constructor:
parent::__construct($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
}
}

class Example {
private $dbh;
public function __construct(dbh $dbh) {
$this-&gt;dbh = $dbh
}
public do_something() {
$sql = 'select * from something';
$this-&gt;dbh-&gt;query($sql);
// etc...
}
}

// do stuff...
$dbh = new dbh();
$test = new Example($dbh);
$test-&gt;do_something();
Copy linkTweet thisAlerts:
@NogDogNov 30.2021 — If you stick with that, you should only have one connection per process (page request). If site traffic and web server configuration allow for enough requests to be processed in parallel, theoretically you could still reach a connection limit, I suppose -- at which point hopefully the site is generating enough revenue that you can afford to upgrade the server config to allow it. ;)
Copy linkTweet thisAlerts:
@kiwisauthorNov 30.2021 — @NogDog#1640030

Perfect, out of interest. Does the connection remain open during the full page load, If I used the connection on the first line then used it’s on another method towards the end which was a longer method calling sub classes and method does it remain open?

Do you force its closure on the bottom of the page?
Copy linkTweet thisAlerts:
@ginerjmNov 30.2021 — A connection only remains while your script is running. And no - you don't have to close it. It just goes away when your script(s) go away.
Copy linkTweet thisAlerts:
@kiwisauthorNov 30.2021 — @ginerjm#1640032

is this this script just the php method running or the entire page?
Copy linkTweet thisAlerts:
@ginerjmNov 30.2021 — A method is a part of a script which is a written piece

A page is a visual thing that you see on your client, not a script.

Basically - unless you have something very complex going on - when your 'page' appears your script is usually already gone since the script has output the html and exited and that html does take a second or 3 to transmit.
Copy linkTweet thisAlerts:
@NogDogNov 30.2021 — @kiwis80#1640033 It's the entire process for any given HTTP request to the server. E.g. if the initial PHP file that starts running when the request comes in initiates the DB object, and then that object gets passed into other functions/methods regardless of whether they get loaded from other included files and such, then it's still the same process and should still be using the same object/connection.
Copy linkTweet thisAlerts:
@kiwisauthorJun 25.2022 — So this error message has started popping up again. I'm not sure why. It was solid for the last 6 months.

Is there a way in which I could test and try isolate the issue? how many connections from my requests vs others on the shared server etc
Copy linkTweet thisAlerts:
@ginerjmJun 25.2022 — You should only have ONE connection period. Make it in your main script and not in your 'class'. And if it is now failing to connect, perhaps you have had a version change somewhere that your code is not ready for?
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644896

I have a dedicated connection class which is reused.
Copy linkTweet thisAlerts:
@sana44Jun 27.2022 — Escort is the most reputable private escort rental service in and offers the most attractive, educated, attractive, and sexually attractive [url=https://elitelahoregirls.com/]Lahore escorts[/url] to its highly-respected customers. Our drivers and chauffeurs have proven track records of providing their clients with services within and around the other major cities across Pakistan. The drivers we employ are trained to serve foreign and domestic customers. They have been professionally trained and have impressive performance records in driving.
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — It shouldnt have to be 'reused'. One call per script. And don't close it at all since PHP will do that in its end-of-life cleanup.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644943

That's just a poor choice of words.

I have a script which 'includes' all my classes which includes my database class. After this I then create an instance of my database and call it $database. I then include this file the top of every single page.

On all my pages when I create objects which require a database connection I pass in my $database variable, this is what I mean by reusing.

I'm still getting the error

index.php
``<i>
</i>include 'includes/load-classes.php';

$person = new Person($database);
$car = new Car($database);<i>

</i>
`</CODE>
load-classes.php
<CODE>
`<i>
</i>require_once '/classes/Dbh.php';
foreach (glob("/classes/*.php") as $filename){
include_once $filename;
}
$database = new database();<i>
</i>
``
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — To avoid any misunderstanding (since this topic is rather old) could you give us the exact error message your are referring to?
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — You said earlier

"how many connections from my requests"

That made believe that you were opening up several db connections which is why I stressed so much that you should only have the one. Perhaps another bad choice of words?
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — Yes, well it would seem that why but I can't see it. Would another user on the shared hosting cause this or would they have their own set of connection limits?

Here's my error

PHP Warning: mysqli::__construct(): (HY000/1040): Too many connections in /home2/user/classes/Dbh.php

Then

PHP Warning: mysqli::prepare(): Couldn't fetch database in /home2/user/classes/carClass.php on line 103
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — The part that says too many connections says to me that you are in a loop while making a connection. Personally I would make my db connection outside of any other class instead of calling it from multiple classes. You only need one so simply call it at the beginning of any main script that is going to need it.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644963

I've realized my dbh.php script was inside the folder of my glob foreach. I was also calling it before.

I've moved it to it's own folder now so it's called once but not within the foreach.

Is this what you mean?
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — The location of the code is NOT the issue. It is how you are calling it. What I was saying is that you should not make your db call/connection from inside any class. You have a class for it that is totally separate from all others. Keep it that way and then make a single call/connection when your main script starts up.

Do this to debug it. Add an echo to your actual connection logic to show that you have just made a connection. Let's see if it repeats. If it does?

And - in my research on this message I see that perhaps other clients could be the issue. If we can ensure that you are not making multiple connections ()with that debug code), then you may have to email your host and ask them why you are getting this error.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644967

Right, so in my load-classes.php file from above do something like this

``<i>
</i>$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";<i>

</i>
``


And pass $conn into my objects created?
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — I thought you said you had a class for your db connection. Doesn't look like it.

You could pass the db handle to the construct of any class that needs it so that you have it ready and don't have to pass it with every method call. Simply assign the value to a private var of the class and use it inside the class.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644969 I did, this is what I have before

``<i>
</i>require_once '/classes/Dbh.php';
foreach (glob("/classes/*.php") as $filename){
include_once $filename;
}
$database = new database();<i>
</i>
``

Including my dbh class first, then all other classes. Creating an instance of my DB object and using it on my page as needed.

I've just to above here I do a manual connection outside a class. It also fails.
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Not sure what your last line is saying but. When you run your revised db code with the debug messages what happens?
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644971

I adjusted it to the above code. Doing it native PHP code and not inside a class. In fact I've done a stand alone page commented out my class-list page (so disabling the site) and I get the follow error

Connection failed: Too many connections
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Did you get your debug message?

If this is a shared-server issue I'm surprised that you keep getting rejected. If someone else is doing something wrong you would think that you wouldn't intersect with them every time you try to run your script.

Please add the debug message to your db class and run your script as you have planned it. I want to see what happens. Also add an echo at the beginning your db connection logic to tell you that you are attempting a connection and then the message that comes after it.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644973

When you say debug script what do you mean?

I've done this

``<i>
</i>if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";<i>
</i>
``


and got this

> Connection failed: Too many connections

Is there something specific I should do for this debug?
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Add another echo at the start of your db connection code to say that you are attempting to connect like I said.

And if you have to ask again, include the ENTIRE db class code this time.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644975

Are you talking about on the class or on the native php code?
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Are you not reading what I am posting? Go back 3 posts of mine and re-read.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644977

Right but I'm not sure how I do this, this is my database class



``<i>
</i>class database extends mysqli {
private $servername = "localhost";
private $username = "admin";
private $password = "password";
private $dbname = "dbname";
public function __construct() {
echo parent::__construct($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
}
}<i>
</i>
``
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Why are you extending this mysqli class? All you want is your own code to make a connection!

Anyway - do this:


class database extends mysqli <br/>
{<br/>
private $servername = "localhost";<br/>
private $username = "admin";<br/>
private $password = "password";<br/>
private $dbname = "dbname";<br/>
public function __construct() <br/>
{<br/>
echo "Attempting to make connection&lt;br&gt;";<br/>
$db = parent::__construct($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);<br/>
echo "Finished making connection&lt;br&gt;";<br/>
return $db;<br/>
}<br/>
}
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644979

To answer your question about extending mysqli class, I'm not sure. It's always been like that.

When I do that, then do

$database = new database();

var_dump($database);

I get this

object(database)#1 (6) { ["client_info"]=> string(14) "mysqlnd 7.4.29" ["client_version"]=> int(70429) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" }
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — I don't care. You chose to do it so live with it.

Please do what I last suggested and let's get to testing this out. I'm getting frustrated.
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644982

I am sorry, I'm just an amateur at this.

Here's what I have

``<i>
</i>class database extends mysqli {
private $servername = "localhost";
private $username = "admin";
private $password = "pass";
private $dbname = "db";

public function construct() {
echo "Attempting to make connection&lt;br&gt;";
$db = parent::construct($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
echo "Finished making connection&lt;br&gt;";
return $db;
}
}

$dbh = new database();
var_dump($dbh);<i>
</i>
``


Which gives me

> object(database)#1 (6) { ["client_info"]=> string(14) "mysqlnd 7.4.29" ["client_version"]=> int(70429) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" }

I wouldn't have expected the echo's in the class to return anything or print on the screen?
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Where did the var dump come from? I didn't mention one.

What happened when you ran the script using the revised db class code with the echos in it?????
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644984

I did var dump because I got nothing when I did just this

$dbh = new database();
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — That's your whole script???

Let's make this even easier for you. In the db class right after the first echo add an exit() line; I want to see that echo.

Do you have error checking turned on like all good programmers do at times like this?
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — @ginerjm#1644986

This is my entire page.

All I get on my page is 'Test Page.'

``<i>
</i>ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

class database extends mysqli {
private $servername = "localhost";
private $username = "admin";
private $password = "pass";
private $dbname = "dbname";

public function construct() {
echo "Attempting to make connection&lt;br&gt;";
exit();
$db = parent::construct($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
echo "Finished making connection&lt;br&gt;";
return $db;
}
}
echo 'Test Page.';
$dbh = new database();<i>
</i>
``
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — I would have to say you have an error in the construct. since you are not getting that echo back.

How about renaming your class to "my_db_connect" and then saying "new my_db_connect"
Copy linkTweet thisAlerts:
@NogDogJun 27.2022 — public function construct() {

...needs to be...

public function __construct() { // double underscore for "magic" method name

PS: and __construct() cannot return anything, so remove the return $db; line. (The fact that you assign the result of new to your variable is sufficient.)
Copy linkTweet thisAlerts:
@kiwisauthorJun 27.2022 — Right, so added the double underscore

As expected I now get;

> Attempting to make connection

> Finished making connection



``<i>
</i> public function __construct() {
echo "Attempting to make connection&lt;br&gt;";
$db = parent::__construct($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
echo "Finished making connection&lt;br&gt;";
return $db;
}<i>
</i>
``
Copy linkTweet thisAlerts:
@ginerjmJun 27.2022 — Sorry I didn't catch that since I don't use classes.

Ok - so now you didn't get the too many message. So what happens when you run this script with the revised class with the messages in it in your normal execution of your script?
Copy linkTweet thisAlerts:
@kiwisauthorJun 28.2022 — @ginerjm#1644992

This issue has been intermittent, it's not currently happening but since the weekend it's been happening multiple times per day. When it next happens I'll try this page and see what it does
Copy linkTweet thisAlerts:
@ginerjmJun 28.2022 — I would guess that if you have run it now and you didn't get repeated messages then it's not your fault.
Copy linkTweet thisAlerts:
@ginerjmJun 28.2022 — I would get rid of that db class tho. Just write a function with the login creds and a param for a dbname in the function header and include that code and call it when you start. Be sure to hide that function outside of the web-accessible tree.
Copy linkTweet thisAlerts:
@kiwisauthorJun 28.2022 — @ginerjm#1644994

Let's see if I get the error over the next few hours

Out of interest my __construct method on other objects look like this.

Do you see any issues here?

I have a create method when creating a object with variables from a form post for example and a createById when creating from a database lookup.

``<i>
</i> public function __construct(database $database){
$this-&gt;dbh = $database;
}<i>
</i>
``
Copy linkTweet thisAlerts:
@kiwisauthorJun 28.2022 — Problem still there, here's my output

> Attempting to make connection
>
> Warning: mysqli::__construct(): (HY000/1040): Too many connections in /home2/user/public_html/mydomain.com/db-test.php on line 14

> Finished making connection
Copy linkTweet thisAlerts:
@ginerjmJun 28.2022 — I don't know why you are showing me this. I dont think you need a class to make a db connection. Period. Just a function that has all the info you need to supply. A simple function. That's all.

function Sql_Connect($dbname)

{

$uid = 'xxx';

$pswd = 'xxx';

if($conn = (normal sqli connect statement))

return $conn;

else

return false;

}

And you would call it with:

if(!$db = Sql_Connect('mydbname'))

{

handle the failure

exit();

}


You may add some things to it as you grow but for now it gets the job done. Besides I don't use classes or Mysqli. Suggest PDO.
Copy linkTweet thisAlerts:
@NogDogJun 28.2022 — > @ginerjm#1644999 Besides I don't use classes

Not really a reason for others to not use them. ;)

I have no issue with doing it either way in this case, especially if everything else is in OOP and this just keeps things consistent in the application structure. 🤷

As to why you get that error, either your current hosting plan is insufficient for your needs, or there's something going on in your app that is creating multiple connections for reasons we can't see without diving into the entire code base, or your queries are too non-performant and requests are piling up behind each other and using all the connections before the earliest ones release them, or something I haven't thought of, or some combination of those, or...?
Copy linkTweet thisAlerts:
@ComfortDriveJun 28.2022 — Hi, thanks for posting this info. We are the[ Coimbatore self-drive car rental](https:/https://comfortdrive.in//) hire us and enjoy your travel.
Copy linkTweet thisAlerts:
@ginerjmJun 28.2022 — I was working on diagnosing the app to see if there were multiple attempts to make connections intra-app. Since there was not a series of reptitive 'connection' messages I ruled it out. And since it doesn't always happen.

As for classes - I just don't use them. Nothing against others diving right in.
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...