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

Fetching a result set


From:

Accessing Databases with Object-Oriented PHP

with David Powers

Video: Fetching a result set

PDO has four different methods for fetching results from a database query. The one you're most likely to use is fetch, which gets the next row from a results set. FetchAll gets all the results at once and stores them as a multi-dimensional array. FetchColumn gets a single column from the next row. You specify which column you want by passing the method, the column number counting from zero as an argument. If no argument is passed, the first column is returned.
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
3h 47m Intermediate Jul 07, 2014

Viewers: in countries Watching now:

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
Subject:
Developer
Software:
PHP
Author:
David Powers

Fetching a result set

PDO has four different methods for fetching results from a database query. The one you're most likely to use is fetch, which gets the next row from a results set. FetchAll gets all the results at once and stores them as a multi-dimensional array. FetchColumn gets a single column from the next row. You specify which column you want by passing the method, the column number counting from zero as an argument. If no argument is passed, the first column is returned.

FetchObject returns the next row as an object. We'll look at creating objects from database results in chapter four. In the meantime let's concentrate on the first three methods. This is pdo_fetch.php which you can find in the chapter 2 02_04 folder of the exercise files. The try block at the top of the page includes the database connection on line three, then on line four we've got a SELECT query, which is stored in a variable called $sql.

We need to execute the query and store the result set. So we can do that on the next line. We'll create a variable called $result. And then we use the database connection and call the query method. We pass at the SQL statement, the query, and this then stores the entire result set in $result. To be able to display that, we can do that one row at a time using the fetch method in a while loop. So, let's scroll down between the two table rows and add a new line on line 29.

This needs to be a php block. Use a while loop. We need to store each row, so we'll it call row. Then the results object. And call the fetch() method. You can see that my editing program is asking me if I want to set a fetch_style. The way in which you set a fetch_style is by passing a PDO fetch() constant as an argument to fetch(). I'm not going to set a style at the moment, we'll look at some of the options in chapter 4, we'll just used the default for the moment.

So let's just add a curly brace, and we need to close the PHP block there and then put the closing PHP brace at the end of the table row. We're using the fetch method in it's default style. This returns the current row as an indexed array and as an associative array. So you got the choice of using the column number, counting from zero, or the column name to display the values. So, let's do that. In this first table cell we'll have a PHP block and we'll use the first row so we're counting from zero.

So row zero. And then in the next one, let's use a column name. Second value was meaning. And then if we copy that we can also use the name of the column for the last one. That's gender. So if we save that, and launch the page in a browser, there are our results displayed. We used the column number for Name and we used the column names for Meaning and Gender but they're all displayed as normal. So let's return to the editing program and take a look at fetchAll and see how that works.

If you open pdo_fetchAll.php. This contains exactly the same SQL statement, the select statement, and it also submits it using the query method, and stores the value in Result. The Fetch All method gets all of the results together and returns them as a multi-dimensional array. So let's do that. We'll save it as $all. I will use the result object and the fetchAll method.

Add in the HTML body of the page. There's a couple of pre-tags, so between them if we have a PHP block and use print_r, we can inspect the contents of that all multidimensional array. So we'll save that and then view the page in a browser. And here's that multidimensional array. The top level array elements, they're the rows. And each of the sub-arrays.

Notice that it contains each value twice. First with the name, and the second time with the column number. When using fetchAll you're unlikely to want both the associative array and the indexed array. So let's go back to the editing program and see how we can alter that. Scroll back up to fetchAll. We can pass fetchAll and argument. We can use a PDO fetch constant. So, it's all in caps. PDO then two colons and then FETCH.

And if we use FETCH_ASSOC and save that, this will give us an associative array. So let's go back to the browser and reload that and now we've just got the names of the columns. And the alternative to FETCH_ASSOC is FETCH_NUM, and no prizes for guessing what this does. It returns them as numbers, the indexed array. So now a quick look at how fetchColumn works. pdo_fetchColumn.php, executes exactly the same query, and then down here fetchColumn is used and it just displays the column.

So, if we display that in the browser, the first column has been displayed. That's default behavior of the fetchColumn() method, it always returns the first column. But you can change which column is displayed by passing the column number as an argument. So if I pass 2 as the argument and save that we should then get the gender. Let's go back to the browser and reload that. This time we've got the gender. And if I change it to 1 and reload, this time we've got the meaning of the name.

The important thing to remember about the fetchColumn method is that the value passed as an argument must be a number counting from zero. You can't use the column name. Another thing you needs to be aware of is that you can't access another column from the same row. Of the three methods we've looked at, fetchColumn is probably the one you'll use least. The fetchAll method is useful when you want the complete result set as an array. By default, fetchAll returns each result twice, first with the name of the column, and the second time with the number of the column.

If you want to change that, parse PDO FETCH_NUM or PDO FETCH_ASOC as an argument to the fetchAll method. And finally, the fetch method is the most widely used, and we'll be coming back to it frequently. This returns one row at a time.

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

Congratulations

You have completed Accessing Databases with Object-Oriented PHP.

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


OK

Upgrade to View Courses Offline

login

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 lynda.com 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.
lynda.com 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 lynda.com 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 lynda.com 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 lynda.com.

Sign up and receive emails about lynda.com 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.