"Could not connect. Too many connections" Error in MySQLi - php

I have the following code
function openDBConn($params){
$conn_mode = $params['conn_mode'];
$db_conn = $params['db_conn'];
//create connections
if(empty($db_conn->info)) {
$db_conn = new mysqli("localhost", $user, $password, "database");
$db_conn->set_charset('UTF8');
$mysqli_error = $db_conn->connect_error;
}
if($mysqli_error !== NULL){
die('Could not connect <br/>'. $mysqli_error);
}else{
return $db_conn;
}
}
//close db connection
function closeDBConn( $params ){
$db_conn = $params['db_conn'];
$db_conn->close;
}
//used as below
$db_conn = openDBConn();
save_new_post( $post_txt, $db_conn );
closeDBConn( array('db_conn'=>$db_conn));
From time to time, I get the "Could not connect. Too many connections" error.
This tends to happen when I have Google bot scanning my website.
This problem seems to have started ever since upgrading to MySQLi from MySQL.
Is there any advice on how ensure all connections are closed?
Thanks

You need to increase the number of connections to your MySQL server (the default is only 100 and typically each page load consumes one connection)
Edit /etc/my.cnf
max_connections = 250
Then restart MySQL
service mysqld restart
http://major.io/2007/01/24/increase-mysql-connection-limit/

Some hosters have a hard limit how many open database connections your are allowed to have. Maybe you want to contact your hoster to know how many you are allowed to open. For websites with hight traffic load more connections can be helpful.

Do you have access to the server directly or is it a hosted solution?
If you have direct access you can check the mySQL config files to see how many connections are allowed and increase it.
If you don't you might want to contact your webhost about increasing the limit and see if they will comply.

Related

Are mysqli persistent connections a solution for: max_user_connections limit? [duplicate]

This question already has an answer here:
What is the best way to minimize number of connections?
(1 answer)
Closed 2 years ago.
When a user logs in the site, an AJAX call is made every 10 seconds, to update data from a delivery service.
It works OK, but at night when the demand for deliveries increases a lot, there begin to be these connection errors.
I'm on a GoDaddy server, so I can't change the 'max_user_connections' to a higher value.
I was reading about persistent connections, but I don't know if it will work.
By adding a "p:" to the connection before the host like this:
$link = mysqli_connect("p:" . DB_HOST, DB_USER, DB_PASS);
I think that when an AJAX call runs a new connection to the DB is made in the PHP file.
Will the persistent connection avoid this and reuses a connection that each users already has?
If a persistent connection is not the right path for this, what could it be?
Errors in PHP Log:
[06-Dec-2020 00:13:22 UTC] PHP Warning: mysqli_connect(): (42000/1226): User 'delivery' has exceeded
the 'max_user_connections' resource (current value: 30) in
/home/ofc1m1i4xaac/public_html/xdelb.com/classes/get_delivering.php on line 15
PHP file get_delivering.php:
<?php
session_start();
session_write_close();
if (!isset($_SESSION['user_id']) ) {
// header("Location: ../index.php");
exit();
}
require_once("../includes/psl-config.php");
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
mysqli_select_db($link, DB_NAME);
mysqli_set_charset($link, "utf8");
$append="";
$number=1;
$result = mysqli_query($link, "SELECT orders_header.`id`, `picking_time`, `delivery_address`, orders_header.`created_at` FROM `orders_header` inner join delivery_guys on delivery_guys.id=dv_guy_id `store_id`=".$_SESSION['user_id'] );
if ( mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
// do stuffs
}
}
mysqli_close($link);
I don't think that persistent connections will help you,
basically your issue of max_connection_error will remain the same or even worst.
So I will suggest take #dave advice and to deploy your website to another host that you can change this configuration or to your own VPS server that ypu can control it and change what ever you want.
This is to docs from PHP website where you can fond more info about persistent connections, advantages and disadvantages
https://www.php.net/manual/en/features.persistent-connections.php
More info and tests results you can find in this website:
https://meta.wikimedia.org/wiki/Why_persistent_connections_are_bad

How do I force reconnecting to my database in php?

I wanted my web system to automatically reconnect to the database if it reaches to maximum user connection. Or is there anyway i could reload the page automatically till it is connected to the database
$conn = new mysqli(DB_HOST,DB_USER,DB_PSWD,DB_NAME);
if($conn->connect_error)
die("Failed to connect database ".$conn->connect_error );
You can setting the retry variable($retry) as a flag to mark the DB connection status with default value you want. While connect DB , if it's ok then update retry flag = 0($retry=0) , else reduce the retry one unit ($retry--). Also you don't die process when have error exception.
You can enclose the connection in a function and call it many times you want to retry the connection:
function connectDB(DB_HOST,DB_USER,DB_PSWD,DB_NAME)
{
return $conn = new mysqli(DB_HOST,DB_USER,DB_PSWD,DB_NAME);
}
if(connectDB()->connect_error)
{
sleep(1);
if(connectDB()->connect_error)
{
die("Failed to connect database ".$conn->connect_error );
}
}
With sleep(1) you delay the script to retry the connection after 1 second.
Anyway, you should find the cause of the connection error and solve it; this solution may help you in the case the server is sometimes slow to respond.

How to connect to remote MYSQL database via php

I have to build an android app which connects to a remote MYSQL webserver and retrieve information for display purpose.
So I did research coz I had no idea where to start. I read an article it mentions the better approach for that is to use php script. And didn’t know anything about how server, database and php works, so I studied php from here “http://www.homeandlearn.co.uk/php/php12p1.html” to understand and downloaded WhampServer to do some testing. On local machine everything worked fine.
But main thing I don’t understand is “HOW TO CONNECT TO REMOTE SERVER/DATABASE”.
It’s obvious that I’m doing something really stupid, I just need help to find out what am I doing wrong.
When we test php script on local machine in webrowse we use "localhost/some.php." But when I want to test same php script on remoter server from my local machine then what and how should I do? Do I need to make some changes in configuration file on server side?
I have done more research before asking this question here to understand remote server connection in php but I still don’t understand. I have gone through almost all the pages within the link below:
https://www.google.co.uk/search?q=connect+to+remote+mysql+webserver+php&rlz=1C1AVSX_enGB447GB448&oq=connect+to+remote+mysql+webserver+php&aqs=chrome.0.69i57j69i62l3.19724j0&sourceid=chrome&ie=UTF-8#fp=5a2359cf96dc5f79&q=how+to+connect+to+remote+mysql+web+server+php
And help would be much appreciated.
If my question is not clear please let me know I'll try to explain more. or think of it as if you have to connect to a remote MySQL server how would you do , means what is the process and steps involved in that.
Thanks everyone.
Edit
I have created a database "dealt3_raj_test" on remote server. and when I type "examplewebserver.CO.UK/myphpscriptname" in my web browser.
It gives me error "An error occurred , You have reached the error page"
<?PHP
$user_name = "dealt3_raj";
$password = "5dN5nh&eMd(vCR$dzk";
$database = "dealt3_raj_test";
$server = "examplewebserver.CO.UK";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_handle)
{
print "Connected";
}
else
{
print "Can not connect to server";
}
if ($db_found)
{
print "DataBase found";
}
else
{
print "DataBase not found";
}
?>
Adding onto #user4035's comment, after opening the connection, use JDBC in your Android/Java code to interact with the database.
That said, it is not good practice. Rather create a web service
Your application may experience latency/connectivity issues. This will impact performance.
Your MySQL server will have to be open to remote connections which is strongly advised against
If your Android App is intended for public usage, it means the database username and password of your MySQL server reside on everyone's phone using your app. Encrypted or not this makes your database server a "step less" secure
Well answered here on SO (JDBC vs Web Service for Android)
use this code to connect with data base
$username = "database user name";
$password = "DB password";
$hostname = "hostname";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("data base name",$dbhandle) or die("Could not select examples");

Store database (PDO) connection

I'm currently writing a PHP application and i noticed that my page loads kinda slow. I takes about 2 seconds (2.0515811443329 to be exact).
I've tracked down what the bottleneck was and it's the part where i'm creating a PDO connection to my MySQL database.
My 'connect()' method doesn't do any exoctic stuff. It simply looks like this:
public function connect ( $database, $host, $username, $password )
{
try
{
$this->db = new \PDO("mysql:dbname=".$database.";host=".$host, $username, $password);
if ( !$this->db )
{
throw new \Exception('Failed to connect to the database!');
}
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
catch ( \Exception $e )
{
echo '<strong>Exception: </strong>'.$e->getMessage();
return false;
}
return true;
}
So when i comment out the call to the 'connect()' method, then my page loads in: 0.035506010055542
This is a huge difference. I can imagine that creating a connection to a database does take up some time, but it takes more than 1,5 seconds... I'm not sure if this is normal?
If it is normal, that it takes up that amount of time then is there a way to store the database connection? Like putting it in a session? Actually, as far as i know storing it in a session isn't possible. But it would be the ideal solution. Storing the connection somewhere until the user closes his browser.
In anyway, is there a problem with my PDO / MySQL? And can i simply store the connection resource somehow? So that i don't have to reconnect to my database everytime for every new page?
PS. I'm doing this all on a localhost (Windows).
You're probably making a connection with 'localhost' as address. Try to change that to '127.0.0.1'. That should fix the problem.
You can create a persistent connection to database using PDO. From the manual
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
And example:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>

Best approach to see if a MySQL Server is up and running

I have a Master - Slave setup for a web application written in PHP. I have a pool of slaves I use for reading, and a Master that is used for writes (and reads if a write has been sent this request). I would like to incorporate an automated system for removed crashed servers from the read pool. Currently I am using:
foreach($readers as $reader)
{
$fp = #fsockopen($reader['host'],3306,$errno,$errstr,1);
if(!$fp)
{
//Remove from pool
}
unset($fp);
}
My primary question is there a more reliable method. I have had quite a few false positives, and vice versa because it is not actually checking for a MySQL server, but rather just a connection on port 3306. Is there a way to check for a MySQL server without raising an exception, which is the behaviour of the PDO and MySQLi extensions in PHP.
You could just use mysql_connect() and check the result for false, and close the connection right away on success. You can make a dummy account with no privileges for that if you like.
That's really the only reliable way, especially if you want to distinguish a running MySQL server from any other random process listening on port 3306.
You could use mysql_ping() to check if a current DB Connection you have open is still alive
Here is the example posted at http://www.php.net/manual/en/function.mysql-ping.php
<?php
set_time_limit(0);
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db = mysql_select_db('mydb');
/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}
/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysql_free_result($result);
/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>
The best way to check if any service is alive is to actually use it. So for MySQL try to connect and execute some fast query, for web server try to fetch some file, for PHP try to fetch some simple script...
For MySQL master/slave setup, one of the solutions is to actually check the state of replication. You can check how many transactions is the slave behind master and decide to stop using that slave when/while it has old data. (I don't do the replication myself, but I think you need to compare the variables Read_Master_Log_Pos and Relay_Log_Pos)

Categories