Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Connecting to a database with PDO


Accessing Databases with Object-Oriented PHP

with David Powers

Video: Connecting to a database with PDO

Connecting to a database with PDO provides you with in-depth training on Developer. Taught by David Powers as part of the Accessing Databases with Object-Oriented PHP
Expand all | Collapse all
  1. 13m 33s
    1. Welcome
      1m 4s
    2. What you should know before watching this course
      2m 8s
    3. Using the exercise files
      4m 56s
    4. Setting SQLite permissions
      1m 11s
    5. A quick primer on using PHP objects
      4m 14s
  2. 10m 12s
    1. Overview of PHP database APIs
      4m 5s
    2. Using prepared statements
      4m 24s
    3. Using transactions
      1m 43s
  3. 48m 57s
    1. Creating a database source name
      2m 3s
    2. Connecting to a database with PDO
      7m 27s
    3. Looping directly over a SELECT query
      3m 49s
    4. Fetching a result set
      8m 3s
    5. Finding the number of results from a SELECT query
      7m 14s
    6. Checking if a SELECT query contains results
      3m 32s
    7. Executing simple non-SELECT queries
      6m 2s
    8. Getting error messages
      7m 17s
    9. Using the quote() method to sanitize user input
      3m 30s
  4. 39m 51s
    1. Binding input and output values
      2m 36s
    2. Using named parameters
      9m 51s
    3. Using question marks as anonymous placeholders
      2m 35s
    4. Passing an array of values to the execute() method
      5m 20s
    5. Binding results to variables
      7m 53s
    6. Executing a transaction
      6m 54s
    7. Closing the cursor before running another query
      4m 42s
  5. 21m 20s
    1. Generating an array from a pair of columns
      2m 44s
    2. Setting an existing object's properties with a database result
      4m 42s
    3. Creating an instance of a specific class with a database result
      6m 1s
    4. Reusing a result set
      7m 53s
  6. 38m 14s
    1. Connecting to a database with MySQLi
      5m 57s
    2. Setting the character set
      1m 57s
    3. Submitting a SELECT query and getting the number of results
      4m 4s
    4. Fetching the result
      7m 35s
    5. Rewinding the result for reuse
      3m 20s
    6. Handling non-SELECT queries
      5m 27s
    7. Getting error messages
      5m 47s
    8. Sanitizing user input with real_escape_string()
      4m 7s
  7. 27m 49s
    1. Initializing and preparing a statement
      4m 17s
    2. Binding parameters and executing a prepared statement
      5m 55s
    3. Binding output variables
      5m 6s
    4. Executing a MySQLi transaction
      7m 5s
    5. Dealing with "commands out of sync" in prepared statements
      5m 26s
  8. 24m 7s
    1. Buffered and unbuffered queries
      4m 19s
    2. Using real_query()
      6m 1s
    3. Freeing resources that are no longer needed
      2m 31s
    4. Submitting multiple queries
      6m 41s
    5. Creating an instance of a class from a result set
      4m 35s
  9. 3m 31s
    1. PDO and MySQLi compared
      3m 31s

please wait ...
Watch the Online Video Course Accessing Databases with Object-Oriented PHP
Video Duration: 7m 27s3h 47m Intermediate Jul 07, 2014

Viewers: in countries Watching now:

View Course Description

Now that PHP has true object-oriented capabilities, it's best practice to access databases using PDO (PHP Data Objects) and MySQLi. These methods produce database-neutral code that works with over a dozen systems, including MySQL, SQL Server, PostgreSQL, and SQLite. Learn how to use PDO and MySQLi to perform basic select, insert, update, and delete operations; improve security with prepared statements; and use transactions to execute multiple queries simultaneously. Author David Powers also covers advanced topics like instantiating custom objects, and compares PDO to MySQLi so you can decide which method is right for you.

Topics include:
  • Connecting to a database with PDO or MySQLi
  • Fetching a result set
  • Executing simple non-SELECT queries
  • Sanitizing user input
  • Binding input and output values
  • Passing an array of values to the execute() method
  • Working with advanced PDO fetch methods
  • Executing a MySQLi transaction
  • Freeing resources that are no longer needed
  • Submitting multiple queries
  • Creating an instance of a class from a result set
David Powers

Connecting to a database with PDO

Now that we've seen how to create a database source name or DSN for PDO, let's connect to the OOPHP database. Because we'll be connecting to the database in every file, it makes sense to use an external file for the database connection. So in the top level of the testing site where you've copied the exercise files for this course, create a new folder called includes. Then inside the includes folder create a PHP file and save it as pdo_connect.php.

The file shouldn't have any HTML code in it, all it needs is the opening PHP tag. To use PDO to connect to MySQL, create a DSN like this. We'll save it as DSN. And it's a string, beginning with the MySQL prefix. A colon, then host=localhost;dbname=oophp.

If you're using a non-standard port for MySQL, you need to add the port as another name value pair. For example, if you're using the default MAMP ports on a Mac, the dsn needs to be changed like this. Let's just duplicate that line and then we'll add the end a semi-colon, port=8889. The order of the name value pairs after the prefix doesn't matter. The exercise files also contain an SQL like database.

So to create a DSN for that let's just go on to another line, dsn equals sqlite, then colon. That needs to be followed by the fully qualified path to the SQLite database file. The file is in the sqlite folder and it's called oophp.db. I'm using xampp on Windows, so my fully qualified path will look like this, c colon slash xampp, then htdocs oophp sqlite, and then the name of the database file which is oophp.db.

If you're on a Mac, you'll need to change that path. For example if you're using mamp, it'll look something like this. Instead of C:/xampp, you'd have a forward slash applications followed by MAMP, and then, it would be the same after that. But these are just examples. The DSN needs to match the database driver you're using and the name or location of the database. I'm going to be using both my SQL and SQlite but we can only use one at a time.

So, I'm going to comment out the last three dsn's. And then we need to create the database connection with a PDO object. So we'll save that as db. And it'll be new PDO, and the first argument to PDO is the database source there. So we've saved that as dsn. And if you're using SQLlight, that's all you need. But for databases that require a username and password, you need to add them as the second and third arguments.

So on MySQL, the username is oophp and the password is lynda, all in lower case. So that's all you need to do to connect to a database using PDO. So we can just save that and we can test it by opening the chapter 2, 02_02 folder inside there is pdo_test.php and if we open that, here on lines ten through to 15 is a little bit of PHP code that will test the connection.

We actually need to create the connection first. We'll do that above the doctype, so add in a PHP block above the doctype. And, when using pdo to connect to a database, you should always use a try catch structure. The try block runs the code, but if PDO throws an exception, you catch it in the catch block. And, this is particularly important with databases that are password protected because an uncaught PDO exception can expose your username and password.

So inside the PHP block at the top, we'll create a try block. After that we'll have a catch block. We're going to catch an exception. We'll call that exception e. And store any error message in error using the get message method. And the code that we want to run needs to go inside the try block. All we need to do is to include our PDO_connect.php file.

To get to the includes folder, we'll need to go up two levels. So, it needs to be require once, then dot dot slash dot dot slash followed by includes, and then pdo_connect.php. So we can just save that, and then go to the browser to test it. And there we are, connection successful.

I hope the same happened with you. Let's just go back to the editing program and if we open pdo_connect.php and introduce an error into our dsn. Let's say we get the wrong name for the database, save that and then go back to the browser and reload that. We then get this message here. We get the SQLSTATE, we get an error number, and then access denied for user oophp local hosted database, ophp, so that tells us what the error is.

So, if you do get an error, read the error message, that should be able to tell you how to correct the problem in your DSN. So let's go back to the editing program and correct that error. Put that o back in there and then I'm going to test this with SQLite. So I'll comment out this DSN and uncomment the SQLite one. I can leave the username and password in there. They'll simply be ignored by SQLite.

So let's just save that and go back to the browser. Refresh that. It says connection successful. There's no indication that we're connecting to a different database, but it's working fine. So now that we've connected to the database with PDO, we're ready to start interacting with it.

There are currently no FAQs about Accessing Databases with Object-Oriented PHP.

Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed Accessing Databases with Object-Oriented PHP.

Return to your organization's learning portal to continue training, or close this page.


Upgrade to View Courses Offline


With our new Desktop App, Annual Premium Members can download courses for Internet-free viewing.

Upgrade Now

After upgrading, download Desktop App Here.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Start your FREE 10-day trial

Begin learning software, business, and creative skills—anytime,
anywhere—with video instruction from recognized industry experts. provides
Unlimited access to over 4,000 courses—more than 100,000 video tutorials
Expert-led instruction
On-the-go learning. Watch from your computer, tablet, or mobile device. Switch back and forth as you choose.
Start Your FREE Trial Now

A trusted source for knowledge.


We provide training to more than 4 million people, and our members tell us that helps them stay ahead of software updates, pick up brand-new skills, switch careers, land promotions, and explore new hobbies. What can we help you do?

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.