Header Ads

Seo Services

PDO TUTORIAL SERIES 4

The last time we made our database class better, and implemented some of the database class methods.

If you haven't read the past tutorials, you can do so if you find it difficult to understand this one:

1. Tutorial 1
2Tutorial 2
3Side Tutorial: Preparation for Tutorial 3
4. Tutorial 3

For today, we are going to improve our database class even more.

I made some changes, see below:



1. I created a protected variable


2. Then i modified my connection method:


3. Create a method to get our connection:


Now, lets test this on our index page:


I wrote the code this way (on a single line) to reduce the number of lines, but basically its a simple SQL statement to select all users from our user table, pdo in-built object, query, was used to attempt carrying out the sql statement, to do this, we need to get our connection to the database and var_dump is just a debugging tool to see what we have in our variable.

If this returns error, then something's wrong... otherwise you should get this:

You can have it this way:


The result is the same.

Now, lets do the actual fetch of the user table (just to further test our code):


Basically, we have the same code as earlier, the difference is the PDO::FETCH_ASSOC statement which is a fetch_style that controls how the next row will be returned to the caller

Our result for the above code:


By the way, don't forget to insert some information into your database.

As you can see, the FETCH_ASSOC returns an array indexed by column name as returned in your result set.

Lets try other fetch styles:


FETCH_BOTH: returns an array indexed by both column name and 0-indexed column number as returned in your result set



You can try others on your own: PDO::FETCH_BOUND, PDO::FETCH_CLASS, PDO::FETCH_LAZY, PDO::FETCH_OBJ.

The fetch style you use is dependent on what you intent to achieve.

Do more reading here: php.net

Finally, for this post, i want to point out or remind you that their are always different ways to achieve the same goal, my method is not a standard, programming method is like a hand-writing, each person's own is different...and just like handwriting, some are more similar than others.

In my next post, which will be this week because i didn't post last week, we will do some cool stuffs with our database and lay the foundation of our application.

Don't forget to share.

No comments