Fetching data with get_var, get_row, and get_results
In the previous lesson, you learned how to access the global $wpdb object, build a prefixed table name, and prepare a query safely with $wpdb->prepare().
Now the next step is learning how WordPress gives data back to you after the query is ready.
There are three very common fetch methods you should know first:
- get_var()
- get_row()
- get_results()
get_var() is for when you want a single value only.
Think of cases like:
- one email
- one post title
- one count
- one option value
So if your query selects only one column from one row, get_var() is usually the simplest choice.
get_row() is for when you want one whole row.
That means one record, but possibly with multiple columns.
For example:
- one user with ID, login, and email
- one post with title and date
- one option row with option_name and option_value
get_results() is for when you want many rows.
That means a list of records.
For example:
- the first 3 users
- the latest 5 posts
- all rows matching a condition
So the practical difference is not really in the SQL itself. The difference is in the shape of the result you expect back.
A good way to think about it:
- get_var() = one value
- get_row() = one row
- get_results() = many rows
Another important point: prepare() and the fetch method do different jobs.
prepare() helps you safely build the SQL query when it has dynamic values.
The fetch method decides how the result should come back after the query runs.
So the normal flow becomes:
- load WordPress
- access global $wpdb
- build table name
- prepare query if needed
- choose the correct fetch method for the result shape
For now, do not worry too much about object vs array return formats. We will keep it simple and just focus on choosing the right method for the right kind of query.
References:
- wpdb class: https://developer.wordpress.org/reference/classes/wpdb/
- get_var(): https://developer.wordpress.org/reference/classes/wpdb/get_var/
- get_row(): https://developer.wordpress.org/reference/classes/wpdb/get_row/
- get_results(): https://developer.wordpress.org/reference/classes/wpdb/get_results/