Posted December 3, 2012 by Spyros in PHP Programming

Database Connection with the PHP PDO Class


In PHP, working with databases using the PDO class is one of the best ways to create a dynamic website. Now, it should be worth mentioning that to work with databases, you need to know how to talk to a database. Please review the SQL section before attempting to use databases in PHP. In SQL, we talk to databases primarily using queries. It has its own syntax and structure that is pretty logical. However, it is also very sensitive because it deals with all of your data. SQL injections can ruin your life. PDO has a couple of excellent ways of overcoming SQL injections using prepared statements. Before we get started, I will not covering all of the SQL queries because I just want you to get the basic idea of how to initiate a connection. Now, Let’s get started:

Database Connection

A database connection is always required to talk to a database because we have to know what data we want to work with. Now, we need to know a few identifiers to access the database, including the location of that database, the database name, username, and password. You should be able to figure all of these out from your hosting provider. It would be too difficult for me to show you how to find them because of the tons of hosting companies that all do it differently.

$host = 'myHostingURL.hostedresource.com';
$dbName = 'databaseName';
$username = 'myUsername';
$password = 'topSecretPassword';

$dbCon = new PDO("mysql:host=". $host . "; dbname=" . $dbName, $username, $password);

Now, you have to change those variables to whatever database settings, username, and password you have. Let’s figure out what the heck is going on here. After the configuration variables, we use $dbCon = new PDO and pass in our various parameters. Of course, you don’t have to split it up like I did, but that makes it much easier to modify down the road. Basically, this is how you set up your link to the database. Your $dbCon variable is now an object of the PDO class. We’ll talk more about this as we see it in action. That is the absolute link to anything and everything you want to do with your data in the database. This was an introduction to using PHP Data Objects.

This was a guest post by Jared Drake, thank you !