Why is PHP PDO DSN a different format for MySQL versus PostgreSQL?

Question!

When I connect to a MySQL database using PDO, the way I need to connect is:

$pdoConnection = new PDO("mysql:host=hostname;dbname=databasename",user,password);

But, for PostgreSQL, the DSN is more standard (IMO):

$pdoConnection = new PDO("pgsql:host=hostname;dbname=databasename;user=username;password=thepassword");

Is there any reason why MySQL cannot use a single string? Or is this just because of the versions I am using (PHP 5.2, MySQL 5.0, PostgreSQL 8.1)?



Answers

Yep, this API inconsistency is a major annoyance.

As a work-around, I pack the actual DSN string with an optional username and password using query-string syntax - then parse and construct like this:

parse_str($connection_string, $params);

$pdo = new PDO($params['dsn'], @$params['username'], @$params['password']);

So for PostgreSQL, use a $connection_string like:

dsn=pgsql:host=localhost;dbname=test;user=root;password=root

And for MySQL, use a string like:

dsn=mysql:host=localhost;dbname=testdb&username=root&password=root

Kind of lame, but it's simple and it works.



As the person that implemented both, I can tell you that the reason is that by passing the string through as-is to postgres (and ODBC) the PDO driver code for those databases does not need to be updated as the underlying library adds new features.

Since mysql does not have its own connection string parsing code, we invented a mechanism for passing data in to the underlying mysql function calls, which have a very specific API with fixed parameters.

No accident; it's very deliberate.



  • LINQ
  • The fact everything goes to IL, which means you can implement any language on top of it and get things like generics and LINQ for very little
  • WF - I know it's complicated and not the greatest implementation of this but if you spend time with it, you find it does work well for it's target purpose.


This video can help you solving your question :)
By: admin