Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 724
Vern Takebayashi Avatar asked Oct 26 '08 01:10

Vern Takebayashi


People also ask

Does PDO work with MySQL?

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.

What is the difference between using MySQL functions and PDO?

MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases.

What is full form of DSN in PHP?

dsn. The Data Source Name, or DSN, contains the information required to connect to the database. In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

Is PHP PDO deprecated?

PHP 8.1: PDO::FETCH_SERIALIZE is deprecated This functionality, however, is broken and is unusable.


2 Answers

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.

like image 86
Wez Furlong Avatar answered Oct 06 '22 09:10

Wez Furlong


This has been resolved in PHP 7.4, as can be seen in the new features.

I have confirmed it locally that we can write:

$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8mb4;user=root;password=') 
like image 45
Alexios Tsiaparas Avatar answered Oct 06 '22 10:10

Alexios Tsiaparas