Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP PDO connects to different database when using persistent connection?

Tags:

php

mysql

pdo

I connect to MySQL using PHP's PDO like this:

$driver_options[PDO::ATTR_PERSISTENT] = true;
$db = new PDO('mysql:host='.$host.';dbname='.$db_name, $user, $pass, $driver_options);

I have 2 databases (let's call them database_A and database_B) on this server and sometimes very strange thing happens. Even though, $db_name is 100% set to 'database_A', connection is made to 'database_B'.

It's happening completely random. I can run the same script 10 times over again and everything is fine. And 11th time this problem happens.

I would never expect this to happen. It gave me a lot of headache. Can anyone explain it ? And is the only solution not to use persistence ?

like image 416
Frodik Avatar asked May 19 '18 15:05

Frodik


People also ask

What are the disadvantages of using persistent connection in PDO?

The biggest drawback to persistent connections is that it limits the number of users you can have browsing your site: if MySQL is configured to only allow 10 concurrent connections at once then when an 11th person tries to browse your site it won't work for them. PDO does not manage the persistence.

What is PDO persistent connection?

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.

How does PDO connect to database?

A PDO database connection requires you to create a new PDO object with a Data Source Name (DSN), Username, and Password. The DSN defines the type of database, the name of the database, and any other information related to the database if required. These are the variables and values we stated inside the dbconfig.

Which type of databases can PDO connect to?

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.


1 Answers

PDO::ATTR_PERSISTENT is partially supported and is dependent on the the PHP version and SQL server you're using. I would recommend never setting this attribute to true in the drive options due to it's instability.

I was able to replicate your case and i found that the ODBC Connection Pooling layer was caching the connection and since your connection is being set to persistent, the cache was being reset each time i made a new connection.

like image 174
Plixxer Avatar answered Oct 02 '22 20:10

Plixxer