I'm wanting to port an existing application from mysqli to PDO, to take advantage of what seems like a much improved api. The app in question is one of many that store their connection information in groups in a .cnf file, like so:

[client]
host=dbserve1

[app1]
database=app1
user=app1_user
password=shhhhh

[app2]
host=dbserve2
database=app2
user=app2_user
password=supersecret

Now with mysqli, I was able to specify the hostname, database, username, and password in the cnf file, and then in PHP just specify an application group to use the corresponding connection info:

$dbh = mysqli_init();
$dbh->options(MYSQLI_OPT_CONNECT_TIMEOUT, 3);
$dbh->options(MYSQLI_READ_DEFAULT_FILE, '/var/mysql/apps.cnf');
$dbh->options(MYSQLI_READ_DEFAULT_GROUP, 'app1');
$dbh->real_connect();

In attempting the same thing with PDO, I can indeed pull the db name, user, and password from the file, but the hostname doesnt seem to take effect. Instead it consistently tries to connect to localhost:

$dbh = new PDO('mysql:', NULL, NULL, array(
	PDO::ATTR_TIMEOUT => 3,
	PDO::MYSQL_ATTR_READ_DEFAULT_FILE => '/var/mysql/apps.cnf',
	PDO::MYSQL_ATTR_READ_DEFAULT_GROUP => 'app1',
));

Isn't there a way to have PDO respect the host specified in the cnf file?

    Sounds like you may have to build the DSN string yourself. 🙁 You could use [man]parse_ini_file[/man] to load the config data into an array, then grab the db server value to create a "host=xxxxx" string to append to the "mysql:".

      Write a Reply...