I am currently running a web application with thousands of visitors and users connecting at the same time. I have a lot of "sleeping" connections in WHM (like 50-65).
I think I am using persistent connections, but my question is, how can I disable this?
This is how I connect to the database:
$dbh = null;
$class = 'PDO';
$database = $settings['database']; //Get the database login information. It is stored in an array();
global $database;
try {
$dsn = "mysql:host=" . $database['host'] . ";dbname=" . $database['db'];
$dbh = new PDO($dsn, $database['user'], $database['pass'], array(PDO::ATTR_PERSISTENT => true));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
//echo 'Connected to Database<br/>';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
I keep getting this error:
SQLSTATE[HY000] [1040] Too many connections
Even though I have updated the max_connections in my.cnf to 5000
Can someone please help me out?
Related
I'm trying to make a connection to the database while having the database config information saperated from the connection.
This is the code I wrote
db config information:
$config = array(
"database" => array(
"host" => "host",
"username" => "username",
"password" => "password",
"name" => "name",
)
);
define("databse_config", $config["database"]);
$config normaly also contains other information not relevant to the question ,that is why I have defined "database_config".
database connection:
require_once "config.php";
define("DB_HOST", databse_config['host']);
define("DB_USERNAME", databse_config['username']);
define("DB_PASSWORD", databse_config['password']);
define("DB_NAME", databse_config['name']);
function connect()
{
$dbhost = DB_HOST;
$dbuser = DB_USERNAME;
$dbpass = DB_PASSWORD;
$dbname = DB_NAME;
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
The problem I keep running in to is that wile trying to execute the function the page keeps loading and eventualy outputs the following error:
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
I'm fairly new to PDO so I also tried the same while using mysqli, which gave the same result.
Any help would be appreciated.
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
This means php tried to establish a TCP/IP connection to your database server AND FAILED. You provided a DB_HOST hostname that's unreachable by network from the location of your php program.
The hostname value could be missing, or it could be wrong. If you provided it by name (mysql-server.example.com), this error message tells you the DNS name lookup succeeded.
So your php sends out a request to the server for a TCP/IP connection. That request never gets a response. That means there's a firewall somewhere blocking the connection, or that there's no network route from your php program to the network.
This all means the $dbhost value is wrong in your new PDO() operation.
Your code could be simplified a lot like this with no loss of modularity. sprintf() helps. Simpler is better for troubleshooting.
require_once "config.php";
function connect()
{
try {
$connectionString = sprintf ("mysql:host=%s;dbname=%s",
database_config['host'],
database_config['name']);
$conn = new PDO($connectionString,
database_config['username'],
database_config['password']);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
And you can echo $connectionString; to see what's in it, and make sure it isn't something bizarre.
I am developing a dynamic website and I'm using both local and remote host. I've tried to implement a code in which I stablish connection first with the localhost. If connection to the locahost is false or can't be established, I go to the second connection (remote server or host). But this time, I want to do something different. Now I want to know if it's possible to connect to two hosts/servers at the same time with no errors. The databases and tables are the same. I'm asking this, because I just want to avoid sql backup. What do you say? Moreover, I want to use the same variable $pdo, so I don't need to change or repeat all connections to the tables.
This is my current code:
<?php
try {
//Local Host - XAMPP
$dsn = 'mysql:host=localhost;dbname=bananas';
$user = 'root';
$pw = '';
$sessionpath = 'C:/xampp/tmp';
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) { //$e
//echo 'Error: '.$e->getMessage();
if(!isset($pdo) || $pdo == false){
try{
//Remote Host
$dsn = 'mysql:host=bananas123;dbname=bananas';
$user = 'mybigbanana';
$pw = '6969';
$sessionpath = '/php_sessions';
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
}
?>
Note: I don't want to do something like having two variables for each connection, like, for example, $pdo and $pdo2. I want only one variable for both connections, which is $pdo.
I am trying to access a database on my web host with a php file that is on the same server. When trying to load the page I get the following error: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111. I cannot find a good answer what it going wrong. Below is my php that I am using. I have my IP address of my database set as my host name.
<?php
$con = mysql_connect("10.123.0.209:3306","username", "password");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("matmac78_macy", $con);
$sql = "SELECT * FROM countries";
$mydata = mysql_query($sql, $con);
while ($record = mysql_fetch_array($mydata)){
echo $record['country'] . " " . $record['population']
echo"<br/>";
}
mysql_close($con);
?>
Any help would be greatly appreciated!
You should switch to using PHP's PDO connection protocol.
$username = 'username';
$password = 'password';
$dbName = 'matmac78_macy';
$host = '10.123.0.209:3306';
try {
$this->database = new \PDO( "mysql:host={$this->host};dbname={$this->dbName}", $this->username, $this->password );
$this->database->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$this->database->setAttribute( \PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC );
return $this->database;
} catch (\PDOException $e) {
throw new \Exception( "Could not establish database connection. \n" ); #Push error message
}
Whenever my website receives too many connections, it's showing my database information.
I have specifically told PDO not to show any error messages with PDO::ERRMODE_SILENT:
$dsn = "mysql:host=" . $database['host'] . ";dbname=" . $database['db'];
$dbh = new PDO($dsn, $database['user'], $database['pass'], array(PDO::ATTR_PERSISTENT => false));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // <== add this line
//echo 'Connected to Database<br/>';
Furthermore I have disabled PHP errors:
error_reporting(0);
ini_set('display_errors', '0');
Why is my PDO showing my sensitive database information to everyone when there are too many connections?
Problem is you're trying to connect to the database BEFORE you set the silent attribute. So during the connection attempt, PDO is still free to scream as loudly as it wants. You need to specify silent as part of the connection attempt itself:
$dbh = new PDO($[..snip..], array(PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
^^^^^^^^^^^
I'm in the process to learn PDO. I started changing my database connection from this:
$dbname = "database1";
mysql_connect(
':/Applications/MAMP/tmp/mysql/mysql.sock',
'root',
'root'
) or die( mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
to PDO connection:
$username = "root";
$password = "root";
try {
$conn = new PDO('mysql:host=localhost;dbname=database1', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
the connection seems to be working but when I try to login on the website (localhost) it doesn't find my username and password.
Do I need to change all my mysql_query to PDO since I changed the database connection to PDO?
Can I please ask you some reference for a good tutorial to help me during this transition phase?
thanks
Yes you do.
Here is a good PDO tutorial and this one