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

What's hot (20)

PDF
DBIx::Class introduction - 2010
leo lapworth
 
PDF
DBD::SQLite
charsbar
 
PDF
Solr's Search Relevancy (Understand Solr's query debug)
Wongnai
 
PPTX
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
Wagdy Mohamed
 
PDF
SQLite in Adobe AIR
Peter Elst
 
PDF
Practical Object Oriented Models In Sql
Karwin Software Solutions LLC
 
PPTX
Building secured wordpress themes and plugins
Tikaram Bhandari
 
PDF
Solr Anti - patterns
Rafał Kuć
 
PPT
Creating a database
Rahul Gupta
 
PPTX
Database Connectivity in PHP
Taha Malampatti
 
PDF
DBIx::Class beginners
leo lapworth
 
PPTX
MS SQL Database basic
wali1195189
 
PPTX
What You Missed in Computer Science
Taylor Lovett
 
PPTX
Mdst 3559-03-01-sql-php
Rafael Alvarado
 
PDF
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
Puppet
 
PDF
4.3 MySQL + PHP
Jalpesh Vasa
 
PPT
jdbc
vikram singh
 
PPTX
Introduction to database
Pongsakorn U-chupala
 
PDF
Introduction to php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
DBIx::Class introduction - 2010
leo lapworth
 
DBD::SQLite
charsbar
 
Solr's Search Relevancy (Understand Solr's query debug)
Wongnai
 
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
Wagdy Mohamed
 
SQLite in Adobe AIR
Peter Elst
 
Practical Object Oriented Models In Sql
Karwin Software Solutions LLC
 
Building secured wordpress themes and plugins
Tikaram Bhandari
 
Solr Anti - patterns
Rafał Kuć
 
Creating a database
Rahul Gupta
 
Database Connectivity in PHP
Taha Malampatti
 
DBIx::Class beginners
leo lapworth
 
MS SQL Database basic
wali1195189
 
What You Missed in Computer Science
Taylor Lovett
 
Mdst 3559-03-01-sql-php
Rafael Alvarado
 
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
Puppet
 
4.3 MySQL + PHP
Jalpesh Vasa
 
Introduction to database
Pongsakorn U-chupala
 
Introduction to php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 

Viewers also liked (20)

PPTX
10 Must Have WordPress Plugins
Affiliate Summit
 
PPT
WordPress Plugin Basics
Amanda Giles
 
PDF
Federal reserve
William Daniels
 
PDF
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
LinnAlexandra
 
PPTX
Build a WordPress theme from HTML5 template @ Telerik
Mario Peshev
 
PPTX
To build a WordPress Theme: Wordcamp Denmark 2014
James Bonham
 
PPSX
WordPress Theme Design and Development Workshop - Day 2
Mizanur Rahaman Mizan
 
ODP
Top 10 WordPress Plugins
Reem Al-Ashry
 
PPTX
Analisis Kinerja Reksadana Saham Syariah Menggunakan Metode Sharpe, Treynor, ...
Arsyil Hendra Saputra
 
PDF
WordPress Database: What's behind those 12 tables
Mauricio Gelves
 
ODP
Hands On Approach To Networking
ayanthi
 
PPTX
PEDOMAN TEKNIS TATA CARA PEMOTONGAN, PENYETORAN DAN PELAPORAN PAJAK PENGHASIL...
Asep suryadi
 
PPT
WordPress Theme Design - Rich Media Institute Workshop
Brendan Sera-Shriar
 
PPTX
Php Vs Phyton
Francis Guison
 
PDF
Tips Pribadi hebat: Mandiri, Sukses, dan Mulia
An Nuur Budi Utama
 
ODP
PHP Web Programming
Muthuselvam RS
 
PDF
Installing WordPress on AWS
Manish Jain
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PDF
WordPress SEO & Optimisation
Joost de Valk
 
10 Must Have WordPress Plugins
Affiliate Summit
 
WordPress Plugin Basics
Amanda Giles
 
Federal reserve
William Daniels
 
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
LinnAlexandra
 
Build a WordPress theme from HTML5 template @ Telerik
Mario Peshev
 
To build a WordPress Theme: Wordcamp Denmark 2014
James Bonham
 
WordPress Theme Design and Development Workshop - Day 2
Mizanur Rahaman Mizan
 
Top 10 WordPress Plugins
Reem Al-Ashry
 
Analisis Kinerja Reksadana Saham Syariah Menggunakan Metode Sharpe, Treynor, ...
Arsyil Hendra Saputra
 
WordPress Database: What's behind those 12 tables
Mauricio Gelves
 
Hands On Approach To Networking
ayanthi
 
PEDOMAN TEKNIS TATA CARA PEMOTONGAN, PENYETORAN DAN PELAPORAN PAJAK PENGHASIL...
Asep suryadi
 
WordPress Theme Design - Rich Media Institute Workshop
Brendan Sera-Shriar
 
Php Vs Phyton
Francis Guison
 
Tips Pribadi hebat: Mandiri, Sukses, dan Mulia
An Nuur Budi Utama
 
PHP Web Programming
Muthuselvam RS
 
Installing WordPress on AWS
Manish Jain
 
JavaScript - An Introduction
Manvendra Singh
 
WordPress SEO & Optimisation
Joost de Valk
 
Ad

Similar to Custom Database Queries in WordPress (20)

PPTX
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
PDF
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin
 
PDF
You Don't Know Query - WordCamp Portland 2011
andrewnacin
 
PPTX
Drupal II: The SQL
ddiers
 
PDF
Drupal - dbtng 25th Anniversary Edition
ddiers
 
PPTX
Wp query
Savita Soni
 
PDF
Wordcamp Fayetteville Pods Presentation (PDF)
mpvanwinkle
 
KEY
Unit testing zend framework apps
Michelangelo van Dam
 
PDF
Unit testing with zend framework tek11
Michelangelo van Dam
 
KEY
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
PDF
Getting Creative with WordPress Queries
DrewAPicture
 
PDF
[WLDN] Supercharging word press development in 2018
Adam Tomat
 
PPTX
Drupal7 dbtng
Nicolas Leroy
 
KEY
The Query the Whole Query and Nothing but the Query
Chris Olbekson
 
PDF
WordPress London 16 May 2012 - You don’t know query
l3rady
 
PDF
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
PPTX
PHP and Cassandra
Dave Gardner
 
PPT
06 Php Mysql Connect Query
Geshan Manandhar
 
PDF
DataMapper
Yehuda Katz
 
PPT
Working with databases in Perl
Laurent Dami
 
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin
 
You Don't Know Query - WordCamp Portland 2011
andrewnacin
 
Drupal II: The SQL
ddiers
 
Drupal - dbtng 25th Anniversary Edition
ddiers
 
Wp query
Savita Soni
 
Wordcamp Fayetteville Pods Presentation (PDF)
mpvanwinkle
 
Unit testing zend framework apps
Michelangelo van Dam
 
Unit testing with zend framework tek11
Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Getting Creative with WordPress Queries
DrewAPicture
 
[WLDN] Supercharging word press development in 2018
Adam Tomat
 
Drupal7 dbtng
Nicolas Leroy
 
The Query the Whole Query and Nothing but the Query
Chris Olbekson
 
WordPress London 16 May 2012 - You don’t know query
l3rady
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
PHP and Cassandra
Dave Gardner
 
06 Php Mysql Connect Query
Geshan Manandhar
 
DataMapper
Yehuda Katz
 
Working with databases in Perl
Laurent Dami
 
Ad

More from topher1kenobe (14)

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

Recently uploaded (20)

PPTX
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
PDF
Python Conference Singapore - 19 Jun 2025
ninefyi
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PDF
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
PPTX
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PPTX
Simplifica la seguridad en la nube y la detección de amenazas con FortiCNAPP
Cristian Garcia G.
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Simplifica la seguridad en la nube y la detección de amenazas con FortiCNAPP
Cristian Garcia G.
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
Practical Applications of AI in Local Government
OnBoard
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 

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