Connecting to MySQL with PDO

With MySQLi, it looks like this:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

But, PDO is a bit different because it can interact 12 different types of databases: Oracle, PostgreSQL, SQLite, MySQL, Cubrid and several others. So, when using it you have to specify which driver you want to use.

Like this:

$conn = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);

Notice the “mysql:host=” bit.

For different drivers, you just change out the “mysql” part.

So, PostgreSQL would be:

$conn = new PDO("pgsql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);

For Oracle, it’d be:

$conn = new PDO("oci:host={$db_host};dbname={$db_name}", $db_user, $db_pass);

And, so on.

Nice thing is…

The code after this doesn’t change for each kind of database. So, you could write the rest of your database interaction code initially for MySQL… then, change to say PostgreSQL.. .and all you have to do is change out the drive designation (mysql, pgsql, oci, etco).

That’s why you hear people recommending you use PDO a lot.

If there’s any chance you might switch to a different database…

It makes sense.

Anyway, this one of the many things you’ll learn inside Module 3 of PHP 101 (which I just uploaded to the site). Along with the basics of CRUD, you’ll learn MySQLi and PDO, prepared statements, building a database class, submitting an HTML for to your database (AND getting data back from it)… and more.

Right now, you can grab all 3 modules for just 27 buqs.

That’s 10 buqs off the regular fee.

Use this link to get it:



Originally published at John Morris.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.