Date post: | 15-Aug-2015 |
Category: |
Technology |
Upload: | topher1kenobe |
View: | 142 times |
Download: | 3 times |
Custom Database Queries in WordPress
An overview of the $wpdb object
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
Developer and Documenter from
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
Should I write my own custom queries with WordPress?
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
NO!WP_Query is efficient and secure.
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
Should I use custom database tables with WordPress?
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
NO!WordPress has an excellent database structure that should accommodate nearly any data.
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
Learn the rules like a pro, so you can break them like an artist” -- Pablo Picasso
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
Why would you write a custom query?
1. You want something really crazy from WordPress tables.
2. You’re accessing data from custom tables.
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
Why would you use custom tables?
1. You need to utilize an existing data set.
2. Whatever you’re building is so weird that it can’t use WordPress’ table structure.
Custom Database Queries in WordPressTopher 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 WordPressTopher DeRosia
@topher1kenobe
What do we do with a table?
● Select● Insert● Update● Delete
Also some debugging and stats analysis.
Custom Database Queries in WordPressTopher 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 WordPressTopher 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 WordPressTopher 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 WordPressTopher 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 WordPressTopher 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 WordPressTopher 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 WordPressTopher 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 WordPressTopher DeRosia
@topher1kenobe
Prepared Statements
Prepared statements allow for much greater security.
$wpdb->query( $wpdb->prepare(
"DELETE FROM $wpdb->postmetaWHERE post_id = %dAND meta_key = %s",
13, 'gargle’ )
);
NOTE: $wpdb knows the names of WordPress tables
Custom Database Queries in WordPressTopher 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 WordPressTopher 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 WordPressTopher 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 WordPressTopher DeRosia
@topher1kenobe
THANKS FOR
LISTENING
Custom Database Queries in WordPressTopher DeRosia
@topher1kenobe
http://topher1kenobe.comFollow me @topher1kenobe