Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Binding results to variables

From: Accessing Databases with Object-Oriented PHP

Video: Binding results to variables

{QTtext}{width:960}{textColor:65280,65280,65280}{justify:center}{timescale:1000}{backColor:0,0,0}{plain}{font:Verdana}{size:20} One of the many advantages of using a prepared statement, is It's exactly the same code as in the prepared statement On lines 11, 12 and 13, we've bound the The first argument to bindColumn is the column that you want to bind.

Binding results to variables

One of the many advantages of using a prepared statement, is the ability to bind individual columns in a ResultSet, to named variables. This makes int easier to embed the results in HTML. This is pdo_output.php, which you can find in the It's exactly the same code as in the prepared statement Chapter03 03_05 folder of the exercise files. with named parameter, that was created earlier in this chapter. On lines 11, 12 and 13, we've bound the input values using the bindValue, and the bindParam methods.

On lines 11, 12 and 13, we've bound the input values using the bindValue, and the bindParam methods. To bind the output values, you use the bindColumn method. And normally, you should do that after the prepared statement has been executed. So we execute the prepared statement on line 14. Let's add a new line after there, and call bindColumn on the statement object. The first argument to bindColumn is the column that you want to bind.

So let's bind the make column. That's a string that you need to put in there. And the second argument, is the variable that you want to bind the result to. So we'll simply call it make, beginning with a dollar sign. As well as, using the column name, bindColumn lets you use the column's position in the result, counting from one. So, yearmade is the second result in our result set. So, let's bind that using a number and we'll bind it to year.

and we'll bind it to year. With PDO, you don't need to bind all of the columns, so let's test this by scrolling down to the table, that displays the results, and replacing the existing values with these new variables, make and year. So, let's go all the way down, at the moment we're assigning the results to a row, so we're using row make. We change row make simply to make and row year made we can change to year.

So if we save that, and test it in a browser, it should work as before. Let's see if we can find some Ford cars. Yes, that's working perfectly. Although you can use the column number instead of the column name, there is a little bit of a problem with it. Let's go back to the editing program, and I'll show you what I mean. Go right back up to the top, and I'm going to select all of the column names in the SQL.

Cut them to my clipboard and replace them with an asterisk, which simply means, select everything from the result. So, if we save that, and go back to the browser, we'll run exactly the same query as before, looking for Ford. And we need to see what happens to this Year column. So, we click search, and everything has changed too. That's the make iID. What has happened is we're selecting everything from our results, and it's now being presented to us in the same order as it is in the tables, and the cars table begins with car ID, the second column is make ID.

table begins with car ID, the second column is make ID. Unless you know the order of the columns in the table, using the numbers is rather dangerous. Let's go back and restore those column names, and we'll bind the output values of mileage, price and description to their own variables. So I'm going to copy this bind column. And paste it there and then duplicate that line twice.

Then what we'll do is, we'll have mileage, and we'll make that miles. Then price, price and description, we'll call that desk. Doesn't matter though, I'm still using two up here because we've now got the column names clearly defined, so it will still have the correct value. So let's go back down to the table, and use these new variables.

So, instead of row mileage, we change that to miles. Row price becomes price. And row description becomes desk. Now what we've done, is we've removed the row, the variable that statement fetch was assigning the values to, row equals statement fetch. This will still work, but we're no longer using row, so you can actually get rid of it. You can just use statement fetch on its own. But then, we have this problem here of what do we have instead of row as our condition? Well the answer is that, as long as you know that we've got a variable that's going to have a value you could use one of those variables.

variable that's going to have a value you could use one of those variables. You need to make sure that the variable that you choose, isn't going to have a null value. But in our particular database, all of the columns have got values, so we can just use the first one. We can use make. And then, we can get rid of road down there as well. If we save that. Go back to the browser, and we run this same Ford one again.

Everything is working correctly now. Let's say we create a search for something that doesn't exist. We've got no cars in there, that are called XYZ, search, no results found. So, using one of the bound variables as the condition to determine whether to display the results that works just as well as using the row. Now, I've tested this with both SQLite and MySQL, and it works as you can see here. But with some databases, this won't work.

The results won't be assigned to named variables, but there is a way in which you can solve that problem. And it makes your code far more portable. So let's just go back to the editing program. What you need to do, is you need to pass a PDO constant as an argument to fetch. So that if you put the cursor inside fetch, and it's all in caps, PDO then two colons and FETCH_BOUND. And we need to do that down here as well.

It's not necessary with all databases, but it does make it more portable. So, that's how you bind the values of a column in a result set to a variable. You use the bindColumn method. Just scroll up to the top, and the bindColumn method takes two arguments. The first one is the column that you want to bind. And the second one is the variable that you want to bind the result to. You can use the column number, counting from one. But I regard that as being less safe than using the column name.

Normally, you should call bindColumn after executing the prepared statement. The only exception is when working with large objects in PostgreSQL. A large object in PostgreS, needs to be bound before the prepared statement is executed, but that's the only exception. In this example, I've used the Fetch Method, but it also works with the Fetchall Method.

Show transcript

This video is part of

Image for Accessing Databases with Object-Oriented PHP
Accessing Databases with Object-Oriented PHP

47 video lessons · 2313 viewers

David Powers
Author

 
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

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
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.

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
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 ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

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:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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.