PDO Tutorial – 04: Running simple SELECT using PDO

There are more ways to retrieve data from a database using PDO. The shortest way, but in my opinion, the too long to remember every single thing in it is as follows:

[javascript src=”https://snipt.net/embed/485899d9c0911902257e5389aa7c90a9/”]

The longer way, but a better one is to keep the query separated:

[javascript src=”https://snipt.net/embed/5162e2f7712c8db4fde86612f99461df/”]

WHERE condition

We could aswell insert the “WHERE” condition inside the queries we wrote earlier, but the best way to query the database when we use “WHERE” conditions is by using placeholders, whether we are talking about positional placeholders or named placeholders:

[javascript src=”https://snipt.net/embed/b265d05474c0ce3f8868169c67e68b45/”]

About the fetch() and fetchAll() methods

As you’ve seen, the fetch() method returns each row in the result set, one after another, or FALSE if there are now rows returned.

On the other hand fetchAll() method returns an array containing all the rows in the result set.

Either way, the methods return an array representing each column if we use fetch(), or an array of rows with each element of the array (representing each row) containing an array of column values.


As you saw in almost all my examples, I am using the FETCH_ASSOC constant when i retrieve results from a database. That is because is easier for me to use the values from the database by naming the their respectiv columns.

So, when you retrieve the result, you usually call the value of the result row as follows: $row[‘column’].


Is a constant that returns an array indexed by column number as returned in your result set, starting with element (column) 0.

That means that you will have to call the first column of the row as follows: $row[0].


Being a memory consumer, the constant FETCH_BOTH will return an array indexed by both column name and number-indexed column number. That means that you can call the columns either by $row[‘firstcolumn’] or $row[0].


This constant will return you an object with property names that correspond to the column names returned in the result set. You will therefore have to get the column by calling it like so: $row->firstcolumn.

For this lesson, I think we’ve learned enough. There are a few more things to say, but I think that for the basics is enough. If you think I missed something, please write me a comment. Thank you

Further reading:

PDO Tutorial for MySQL Developers

Courses Web PHP PDO – Select query, fetch

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.