SlideShare a Scribd company logo
Custom Database Queries
in WordPress
An overview of the $wpdb object
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Developer and Documenter from
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Should I write my own custom
queries with WordPress?
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
NO!
WP_Query is efficient and secure.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Should I use custom database
tables with WordPress?
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
NO!
WordPress has an excellent database structure
that should accommodate nearly any data.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Learn the rules like a pro, so you can break them like an artist” -- Pablo
Picasso
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Why would you write a custom query?
1. You want something really crazy from
WordPress tables.
1. You’re accessing data from custom tables.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Why would you use custom tables?
1. You need to utilize an existing data set.
1. Whatever you’re building is so weird that it
can’t use WordPress’ table structure.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
How do we talk to MySQL inside
WordPress?
The $wpdb object is instantiated very early and
provides a number of methods for communicating
with the database.
Example:
$results = $wpdb->get_results( 'SELECT * FROM
wp_options WHERE option_id = 1', OBJECT );
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
What do we do with a table?
● Select
● Insert
● Update
● Delete
Also some debugging and stats analysis.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
SELECT
get_var()
$wpdb->get_var( $query, column_offset, row_offset );
The get_var function returns a single variable from the database. The
entire result of the query is cached for later use. Returns NULL if no
result is found.
get_row()
$wpdb->get_row($query, output_type, row_offset);
Retrieves an entire row. Can return an object, associative array, or
numerically indexed array. Caches all matching rows.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
SELECT
get_col()
$wpdb->get_col( $query, column_offset );
Returns a one dimensional array of a column.
get_results()
$wpdb->get_results( $query, output_type );
Generic, multiple row results can be pulled from the database with
get_results. Returns the entire query result as an array.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
INSERT
$wpdb->insert( $table, $data, $format );
$wpdb->insert(
'table',
array(
'column1' => 'value1',
'column2' => 123
),
array(
'%s',
'%d'
)
);
This function returns false if the row could not be inserted. Otherwise, it returns the number of
affected rows (which will always be 1).
After insert, the ID generated for the AUTO_INCREMENT column can be accessed with:
$wpdb->insert_id
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
UPDATE
$wpdb->update( $table, $data, $where, $format = null, $where_format = null );
$wpdb->update(
'table',
array(
'column1' => 'value1', // string
'column2' => 'value2' // integer (number)
),
array( 'ID' => 1 ),
array(
'%s', // value1
'%d' // value2
),
array( '%d' )
);
Return values: This function returns the number of rows updated, or false if there is an error. Keep in mind that if the $data
matches what is already in the database, no rows will be updated, so 0 will be returned. Because of this, you should
probably check the return with false === $result
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
DELETE
$wpdb->delete( $table, $where, $where_format = null );
$wpdb->delete( 'table', array( 'ID' => 1 ), array( '%d' ) );
Returns the number of rows updated, or false on error.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
REPLACE
$wpdb->replace( $table, $data, $format );
$wpdb->replace(
'table',
array(
'indexed_id' => 1,
'column1' => 'value1',
'column2' => 123
),
array(
'%d',
'%s',
'%d'
)
);
After replace, the ID generated for the AUTO_INCREMENT column can be accessed with:
$wpdb->insert_id
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
query()
$wpdb->query( $query );
The query() function allows you to send any query.
IMPORTANT: Returns an integer value indicating the number of rows
affected/selected for SELECT, INSERT, DELETE, UPDATE, etc.
For CREATE, ALTER, TRUNCATE and DROP SQL statements, (which
affect whole tables instead of specific rows) this function returns TRUE
on success.
If a MySQL error is encountered, the function will return FALSE.
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Prepared Statements
Prepared statements allow for much greater security.
$wpdb->query(
$wpdb->prepare(
"
DELETE FROM $wpdb->postmeta
WHERE post_id = %d
AND meta_key = %s
",
13, 'gargle’
)
);
NOTE: $wpdb knows the names of WordPress tables
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Prepared Statements
Another example:
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare(
"
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value )
VALUES ( %d, %s, %s )
",
10,
$metakey,
$metavalue
) );
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Show and Hide MySQL errors
You can turn error echoing on and off with the show_errors and hide_errors,
respectively.
<?php $wpdb->show_errors(); ?>
<?php $wpdb->hide_errors(); ?>
You can also print the error (if any) generated by the most recent query with
print_error.
<?php $wpdb->print_error(); ?>
Note: If you are running WordPress Multisite, you must define the DIEONDBERROR
constant for database errors to display like so:
<?php define( 'DIEONDBERROR', true ); ?>
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
Important details
● get_results() is the most flexible method, BUT
● Use prepare() whenever possible
● Be consistent
● Read everything on the Codex
https://codex.wordpress.org/Class_Reference/wpdb
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
THANKS FOR
LISTENING
Custom Database Queries in WordPress
Topher DeRosia
@topher1kenobe
http://topher1kenobe.com
Follow me @topher1kenobe

More Related Content

PPTX
Mysql
PPT
Database presentation
PPT
MYSQL - PHP Database Connectivity
PDF
lab56_db
PDF
PuppetConf 2017: Hiera 5: The Full Data Enchilada- Hendrik Lindberg, Puppet
PDF
Getting Creative with WordPress Queries, Again
PDF
PHP and Mysql
Mysql
Database presentation
MYSQL - PHP Database Connectivity
lab56_db
PuppetConf 2017: Hiera 5: The Full Data Enchilada- Hendrik Lindberg, Puppet
Getting Creative with WordPress Queries, Again
PHP and Mysql

What's hot (20)

PDF
DBIx::Class introduction - 2010
PDF
DBD::SQLite
PDF
Solr's Search Relevancy (Understand Solr's query debug)
PPTX
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
PDF
SQLite in Adobe AIR
PDF
Practical Object Oriented Models In Sql
PPTX
Building secured wordpress themes and plugins
PDF
Solr Anti - patterns
PPT
Creating a database
PPTX
Database Connectivity in PHP
PDF
DBIx::Class beginners
PPTX
MS SQL Database basic
PPTX
What You Missed in Computer Science
PPTX
Mdst 3559-03-01-sql-php
PDF
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
PDF
4.3 MySQL + PHP
PPT
PPTX
Introduction to database
PDF
Introduction to php database connectivity
DBIx::Class introduction - 2010
DBD::SQLite
Solr's Search Relevancy (Understand Solr's query debug)
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
SQLite in Adobe AIR
Practical Object Oriented Models In Sql
Building secured wordpress themes and plugins
Solr Anti - patterns
Creating a database
Database Connectivity in PHP
DBIx::Class beginners
MS SQL Database basic
What You Missed in Computer Science
Mdst 3559-03-01-sql-php
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
4.3 MySQL + PHP
Introduction to database
Introduction to php database connectivity
Ad

Viewers also liked (20)

PPTX
10 Must Have WordPress Plugins
PPT
WordPress Plugin Basics
PDF
Federal reserve
PDF
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
PPTX
Build a WordPress theme from HTML5 template @ Telerik
PPTX
To build a WordPress Theme: Wordcamp Denmark 2014
PPSX
WordPress Theme Design and Development Workshop - Day 2
ODP
Top 10 WordPress Plugins
PPTX
Analisis Kinerja Reksadana Saham Syariah Menggunakan Metode Sharpe, Treynor, ...
PDF
WordPress Database: What's behind those 12 tables
ODP
Hands On Approach To Networking
PPTX
PEDOMAN TEKNIS TATA CARA PEMOTONGAN, PENYETORAN DAN PELAPORAN PAJAK PENGHASIL...
PPT
WordPress Theme Design - Rich Media Institute Workshop
PPTX
Php Vs Phyton
PDF
Tips Pribadi hebat: Mandiri, Sukses, dan Mulia
ODP
PHP Web Programming
PDF
Installing WordPress on AWS
PPT
JavaScript - An Introduction
PDF
WordPress SEO & Optimisation
10 Must Have WordPress Plugins
WordPress Plugin Basics
Federal reserve
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Build a WordPress theme from HTML5 template @ Telerik
To build a WordPress Theme: Wordcamp Denmark 2014
WordPress Theme Design and Development Workshop - Day 2
Top 10 WordPress Plugins
Analisis Kinerja Reksadana Saham Syariah Menggunakan Metode Sharpe, Treynor, ...
WordPress Database: What's behind those 12 tables
Hands On Approach To Networking
PEDOMAN TEKNIS TATA CARA PEMOTONGAN, PENYETORAN DAN PELAPORAN PAJAK PENGHASIL...
WordPress Theme Design - Rich Media Institute Workshop
Php Vs Phyton
Tips Pribadi hebat: Mandiri, Sukses, dan Mulia
PHP Web Programming
Installing WordPress on AWS
JavaScript - An Introduction
WordPress SEO & Optimisation
Ad

Similar to Custom Database Queries in WordPress (20)

PPTX
You don’t know query - WordCamp UK Edinburgh 2012
PDF
You Don't Know Query (WordCamp Netherlands 2012)
PDF
You Don't Know Query - WordCamp Portland 2011
PPTX
Drupal II: The SQL
PDF
Drupal - dbtng 25th Anniversary Edition
PPTX
Wp query
PDF
Wordcamp Fayetteville Pods Presentation (PDF)
KEY
Unit testing zend framework apps
PDF
Unit testing with zend framework tek11
KEY
Unit testing with zend framework PHPBenelux
PDF
Getting Creative with WordPress Queries
PDF
[WLDN] Supercharging word press development in 2018
PPTX
Drupal7 dbtng
KEY
The Query the Whole Query and Nothing but the Query
PDF
WordPress London 16 May 2012 - You don’t know query
PDF
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
PPTX
PHP and Cassandra
PPT
06 Php Mysql Connect Query
PDF
DataMapper
PPT
Working with databases in Perl
You don’t know query - WordCamp UK Edinburgh 2012
You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query - WordCamp Portland 2011
Drupal II: The SQL
Drupal - dbtng 25th Anniversary Edition
Wp query
Wordcamp Fayetteville Pods Presentation (PDF)
Unit testing zend framework apps
Unit testing with zend framework tek11
Unit testing with zend framework PHPBenelux
Getting Creative with WordPress Queries
[WLDN] Supercharging word press development in 2018
Drupal7 dbtng
The Query the Whole Query and Nothing but the Query
WordPress London 16 May 2012 - You don’t know query
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
PHP and Cassandra
06 Php Mysql Connect Query
DataMapper
Working with databases in Perl

More from topher1kenobe (14)

PDF
How To Increase Ecommerce Conversions
PDF
Build Ecommerce Sites With Confidence (Demystifying Ecommerce), WordCamp Los ...
PDF
Build Ecommerce Sites With Confidence (Demystifying Ecommerce)
PDF
6 Ecommerce Trends Altering the Ecommerce Landscape, and changing which strat...
PDF
Introduction to the WordPress Transients API
PDF
Talking to Other Sites with the WP HTTP API
PPTX
What’s a REST API and why should I care?
PPTX
Working with WP_Query in WordPress
PPTX
HeroPress: A Case Study
PPTX
Introduction to WordPress Child Theming, WordCamp Kansas City, 2015
PPTX
Intro to Plugin Development, Miami WordCamp, 2015
PPTX
Introduction to WordPress Plugin Development, WordCamp North Canton, 2015
PDF
WordCamp Ann Arbor 2014: Site Caching, From Nothing to Everything
PPTX
Command Line Awesome, WordCamp Grand Rapids 2014
How To Increase Ecommerce Conversions
Build Ecommerce Sites With Confidence (Demystifying Ecommerce), WordCamp Los ...
Build Ecommerce Sites With Confidence (Demystifying Ecommerce)
6 Ecommerce Trends Altering the Ecommerce Landscape, and changing which strat...
Introduction to the WordPress Transients API
Talking to Other Sites with the WP HTTP API
What’s a REST API and why should I care?
Working with WP_Query in WordPress
HeroPress: A Case Study
Introduction to WordPress Child Theming, WordCamp Kansas City, 2015
Intro to Plugin Development, Miami WordCamp, 2015
Introduction to WordPress Plugin Development, WordCamp North Canton, 2015
WordCamp Ann Arbor 2014: Site Caching, From Nothing to Everything
Command Line Awesome, WordCamp Grand Rapids 2014

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation theory and applications.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Empathic Computing: Creating Shared Understanding
PDF
KodekX | Application Modernization Development
PDF
Approach and Philosophy of On baking technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Cloud computing and distributed systems.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Unlocking AI with Model Context Protocol (MCP)
Encapsulation theory and applications.pdf
Review of recent advances in non-invasive hemoglobin estimation
Advanced methodologies resolving dimensionality complications for autism neur...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Empathic Computing: Creating Shared Understanding
KodekX | Application Modernization Development
Approach and Philosophy of On baking technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Big Data Technologies - Introduction.pptx
sap open course for s4hana steps from ECC to s4
Cloud computing and distributed systems.
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Dropbox Q2 2025 Financial Results & Investor Presentation
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MIND Revenue Release Quarter 2 2025 Press Release
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

Custom Database Queries in WordPress

  • 1. Custom Database Queries in WordPress An overview of the $wpdb object Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 2. Developer and Documenter from Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 3. Should I write my own custom queries with WordPress? Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 4. NO! WP_Query is efficient and secure. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 5. Should I use custom database tables with WordPress? Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 6. NO! WordPress has an excellent database structure that should accommodate nearly any data. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 7. Learn the rules like a pro, so you can break them like an artist” -- Pablo Picasso Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 8. Why would you write a custom query? 1. You want something really crazy from WordPress tables. 1. You’re accessing data from custom tables. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 9. Why would you use custom tables? 1. You need to utilize an existing data set. 1. Whatever you’re building is so weird that it can’t use WordPress’ table structure. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 10. How do we talk to MySQL inside WordPress? The $wpdb object is instantiated very early and provides a number of methods for communicating with the database. Example: $results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT ); Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 11. What do we do with a table? ● Select ● Insert ● Update ● Delete Also some debugging and stats analysis. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 12. SELECT get_var() $wpdb->get_var( $query, column_offset, row_offset ); The get_var function returns a single variable from the database. The entire result of the query is cached for later use. Returns NULL if no result is found. get_row() $wpdb->get_row($query, output_type, row_offset); Retrieves an entire row. Can return an object, associative array, or numerically indexed array. Caches all matching rows. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 13. SELECT get_col() $wpdb->get_col( $query, column_offset ); Returns a one dimensional array of a column. get_results() $wpdb->get_results( $query, output_type ); Generic, multiple row results can be pulled from the database with get_results. Returns the entire query result as an array. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 14. INSERT $wpdb->insert( $table, $data, $format ); $wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123 ), array( '%s', '%d' ) ); This function returns false if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1). After insert, the ID generated for the AUTO_INCREMENT column can be accessed with: $wpdb->insert_id Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 15. UPDATE $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); $wpdb->update( 'table', array( 'column1' => 'value1', // string 'column2' => 'value2' // integer (number) ), array( 'ID' => 1 ), array( '%s', // value1 '%d' // value2 ), array( '%d' ) ); Return values: This function returns the number of rows updated, or false if there is an error. Keep in mind that if the $data matches what is already in the database, no rows will be updated, so 0 will be returned. Because of this, you should probably check the return with false === $result Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 16. DELETE $wpdb->delete( $table, $where, $where_format = null ); $wpdb->delete( 'table', array( 'ID' => 1 ), array( '%d' ) ); Returns the number of rows updated, or false on error. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 17. REPLACE $wpdb->replace( $table, $data, $format ); $wpdb->replace( 'table', array( 'indexed_id' => 1, 'column1' => 'value1', 'column2' => 123 ), array( '%d', '%s', '%d' ) ); After replace, the ID generated for the AUTO_INCREMENT column can be accessed with: $wpdb->insert_id Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 18. query() $wpdb->query( $query ); The query() function allows you to send any query. IMPORTANT: Returns an integer value indicating the number of rows affected/selected for SELECT, INSERT, DELETE, UPDATE, etc. For CREATE, ALTER, TRUNCATE and DROP SQL statements, (which affect whole tables instead of specific rows) this function returns TRUE on success. If a MySQL error is encountered, the function will return FALSE. Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 19. Prepared Statements Prepared statements allow for much greater security. $wpdb->query( $wpdb->prepare( " DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s ", 13, 'gargle’ ) ); NOTE: $wpdb knows the names of WordPress tables Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 20. Prepared Statements Another example: $metakey = "Harriet's Adages"; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; $wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s ) ", 10, $metakey, $metavalue ) ); Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 21. Show and Hide MySQL errors You can turn error echoing on and off with the show_errors and hide_errors, respectively. <?php $wpdb->show_errors(); ?> <?php $wpdb->hide_errors(); ?> You can also print the error (if any) generated by the most recent query with print_error. <?php $wpdb->print_error(); ?> Note: If you are running WordPress Multisite, you must define the DIEONDBERROR constant for database errors to display like so: <?php define( 'DIEONDBERROR', true ); ?> Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 22. Important details ● get_results() is the most flexible method, BUT ● Use prepare() whenever possible ● Be consistent ● Read everything on the Codex https://codex.wordpress.org/Class_Reference/wpdb Custom Database Queries in WordPress Topher DeRosia @topher1kenobe
  • 23. THANKS FOR LISTENING Custom Database Queries in WordPress Topher DeRosia @topher1kenobe http://topher1kenobe.com Follow me @topher1kenobe