Fetching Records with PHP PDO - Coding Cyber

Fetching Records with PHP PDO

Here in this step, you will learn about fetching records from the database. You will learn about different methods available in PDO to fetch results from the database.

First of all, you will see about fetch method. After that fetch all method then fetch column method and getting the number of rows in result with PHP PDO. And also you will learn about PDO fetch styles to get the numeric array or associative array.

Other Articles in Learn PHP PDO

1 Fetching Results with Fetch Method

With fetch method in PDO, we can get single record result from the entire result set. To get multiple records with fetch method we should use a loop. While loop works with this fetch method.

Here you can see the example code to fetch the records with fetch method combined with while loop.

After printing the row you can see an array with numeric array and associative array. You can get an only numeric array or an associative array with PDO fetch styles, you will learn about these PDO fetch styles in the last step.

You can display the full name with associative array and the numeric array.

2 Fetching Results with FetchAll Method

FetchAll method gets all the results from the database based on the query. It is same as the fetch method but the difference is it returns an entire result set.

You can use the loop to go through each array. After printing the result, you will understand the difference between fetch and fetchAll methods.

3 Fetching Results with FetchColumn Method

The fetchColumn method is used to get only column based results. It only fetches one column result. If you are not passing any column number fetchColumn by default fetches the first column result in the database.

You should always pass numeric column number, not the column name. Here, I’m showing an example of fetchColumn with While loop to get all the email address from the table.

I’m displaying emails in the browser with echo PHP function.

4 Counting Number of Rows in PDO

To get the number of rows from the result set, you can use the rowCount method. This rowCount method works same like mysqli_num_rows PHP function.

Here is an example to get the number of rows from the result set.

Related Posts
No related posts for this content
Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: