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

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

What's hot (20)

DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)
 
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Sessi...
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIR
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
 
Building secured wordpress themes and plugins
Building secured wordpress themes and pluginsBuilding secured wordpress themes and plugins
Building secured wordpress themes and plugins
 
Solr Anti - patterns
Solr Anti - patternsSolr Anti - patterns
Solr Anti - patterns
 
Creating a database
Creating a databaseCreating a database
Creating a database
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basic
 
What You Missed in Computer Science
What You Missed in Computer ScienceWhat You Missed in Computer Science
What You Missed in Computer Science
 
Mdst 3559-03-01-sql-php
Mdst 3559-03-01-sql-phpMdst 3559-03-01-sql-php
Mdst 3559-03-01-sql-php
 
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
Delegated Configuration with Multiple Hiera Databases - PuppetConf 2014
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
jdbc
jdbcjdbc
jdbc
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
Perl
PerlPerl
Perl
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 

Viewers also liked

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

Viewers also liked (20)

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

Similar to Custom Database Queries in WordPress

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

Similar to Custom Database Queries in WordPress (20)

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

More from topher1kenobe

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

More from topher1kenobe (14)

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

Recently uploaded

Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
CAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on BlockchainCAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on Blockchain
Claudio Di Ciccio
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 

Recently uploaded (20)

Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
CAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on BlockchainCAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on Blockchain
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 

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