Advertisement

Using WordPress for Web Application Development: Features: Saving Data

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

This post is part of a series called Using WordPress for Web Application Development.
Using WordPress for Web Application Development: Features: Email

When it comes to the web, almost any application that runs within your browser is backed by a data store of some type. Usually, these data stores are in the form of a type of database.

Until recently, most applications were built on top of some type of SQL database, but with the rise of document-based databases such as CouchDB, other applications have begun to use other backends as well.

Not only that, with HTML5 and browsers implementing services for localStorage, we're actually able to begin to store some data on the client side. Obviously, this isn't something that you'd want to do permanently, but it does grant a level of flexibility and power that we've not recently had.

Anyway, in the classical vein of web applications, WordPress is a database-backed application that uses a MySQL database to store its information.

But this series is about building applications on top of WordPress. To that end, it's important to understand not only how to save information, but how to retrieve information, as well.

Of course, when working with data serialization, it's also important to take into account that users may try to insert malicious data into the database. As such, it's our responsibility to properly sanitize data when inserting the data into the database, as well as making sure we're properly escaping the data as we retrieve it from the database.

In this article, we're going to take a look at the APIs that WordPress offers for serializing information, and the facilities available for sanitizing data. Then we'll round out the article by taking taking a look at how to safely retrieve information from the database.


Data Storage

Obviously, one of the primary differentiators between normal websites and web applications is their ability to manage data that's stored in some type of database. Typically, this also means that information is stored on a per user basis (but not always).

Anyway, out-of-the-box, WordPress offers a variety of APIs that make it easy to store and retrieve data. And perhaps the nicest thing about saving data to the WordPress database is that once you grasp how one API works, you'll usually have an intuition as to how the rest of them work.

So with that said, let's get started at looking at how we save information in the WordPress database.

Understanding the Database

For those of you who are not already familiar, WordPress only consists of a handful of tables. For the purposes of this discussion, we're primarily concerned with knowing about the following tables:

  • wp_options. The options table is responsible for storing pieces of information that are related to preferences, configuration, anything that's related to settings that are applicable site wide.
  • wp_posts. This table stores data related to posts. Though we won't directly be working with this table, it's important to understand that it does exist so we can work with post meta information.
  • wp_postmeta. As previously mentioned, this table is responsible for holding meta information related to individual posts. And since posts can represent pages, posts, and custom post types, then this is where you store information related to each of your post types. It's extremely flexible in the type of data stored, so you really can have a lot of power in terms of how you relate information to posts (regardless of the type that they are defined as).
  • wp_comments. This table should go without saying, but this is where all comments for both posts, pages, and custom post types are stored. Like wp_posts, this is not where we will be writing data directly, but it's important to understand that this table exists and that there's a comment meta data table that we can access when writing information to the table.
  • wp_commentmeta. As mentioned, like wp_postmeta, this is where meta data about comments is kept. And granted, although you don't necessarily be working with comments in web applications across the board, you may end up having a blog component to your application. And in that case, it helps to know how you can read data from, and write data to, the table.

Obviously, this is just a high-level survey of some of the database tables that power WordPress. If you want to be familiar with the rest of the information if only for your own edification then be sure to review the database description.

Nonetheless, this should be good enough to get us standard in reading and writing information to the database.

Writing Data to the Database

At this point, we have enough information about the database layer to begin taking a survey of the APIs that are available in the WordPress application layer that allow us to take information provided either by ourselves and/or by user input.

The Options Table

Now, writing information to each of the above tables is really easy.

  1. It's a matter of understanding the available APIs
  2. It's important to know how to sanitize the data

First, we're going to take a look at the functions that are available for reading, writing, and updating information in the WordPress options tables.

Adding and Updating Options

WordPress provides two specification API functions for writing data to the database. One comes in the form of adding information, one comes in the form of updating information.

To add information to the WordPress options table, you'd use the following API function.

add_option accepts three parameters:

  1. A key - or a unique identifier for the information
  2. The value of the data to be stored

For example, if we wanted to store information, such as my name, then we'd do something like this:

add_option( 'my-name', 'tom mcfarlin' );

If, on the other hand, we wanted to take something coming from the $_POST collection, then we may do something like this:

if ( isset( $_POST['value'] ) && ! empty( $_POST['value'] ) {
	add_option( 'my-value', $_POST['value'] );
}

Updating options is much different. It follows the same schema and can actually be used in place of add_option because if the option doesn't already exist, it will create it.

For the sake of belaboring the point, I won't go into much more information about this particular function. Essentially, update_option will:

  • Add the option if it doesn't already exists
  • Overwrite the existing value if it does exist

Not bad, right?

A Word About Theme Mod

For those of you who have done work with WordPress themes - especially when using the Theme Customizer - then you're likely familiar with the set_theme_mod function.

This particular API function is not exactly relevant to build web applications with WordPress; however, to be complete, I wanted to be able to show all of the APIs that are responsible for writing data to the database.

Note specifically from the Codex:

Creates or updates a modification setting for the current theme. Along with get_theme_mod() this function sometimes offers theme developers a simpler alternative to the Settings API when there is a need to handle basic theme-specific settings.

This is clearly relegated to working with themes.

The Post Meta and Comment Meta Tables

Honestly, working with post meta is not much different than working with options. In fact, you can even consider the API functions for serializing post meta data and the comment meta data almost identical to how options are stored in the wp_options database.

In short, the API functions take in three piece of informations:

  1. The element ID
  2. The data key
  3. The data value

So in the case of saving post information, the element ID would correspond to the post ID; in the case of the comments, the element ID would correspond to the comment ID.

And just as is the case with saving data to the options table, it's important to note that adding an option will introduce the option into the database, and updating the option will create the option if it doesn't already exist, and then overwrite the existing value in the database.

Case in point, saving information into the post meta table:

add_post_meta( get_the_ID(), 'my-post-information', 'This is my favorite post.' );

And, say, updating information in the comment meta table would look like:

update_post_meta( get_the_ID(), 'my-post-information', 'This is my favorite post.' );

Alternatively, you may need to use the global $post variable if the method isn't being called within The Loop. For example:

global $post;
add_post_meta( $post->ID, 'my-post-information', 'This is my favorite post.' );

And in order to write data to the comment meta tables, you follow the exact same format, except you use add_comment_meta and update_comment_meta.

But now that we've covered how to save information into the options table, the post meta table, and the comment meta table, how do we actually make sure that no dangerous information is saved in the database?

Easy: Data sanitization.


Sanitizing Data

When it comes to saving data to the database, one of the most important things that developers must do is sanitize all of the information that's coming from the user and entering the database.

Now the thing about sanitizing data is that it depends on the data that you're having to save. For example, there are very few times where you'll actually want to save markup, SQL, or other types of source code into the database.

In order to prevent this, you'll likely want to use the PHP functions such as strip_tags and stripslahes in order to clean up the information.

For example:

if ( isset( $_POST['value'] ) && ! empty( $_POST['value'] ) {

	$clean_value = strip_tags( stripslashes( $_POST['value'] ) );
	add_option( 'my-value', $clean_value );
}

Of course, to be absolutely clear, this is but an example of how to sanitize information. Your implementation may vary based on the type of application that you are building. The point of sharing this information is showing one of many ideas on how to clean information for saving it into the WordPress database.

Then again, these aren't the only ways that we can sanitize values. Remember to follow up on the facilities that WordPress provides out-of-the-box:

  1. sanitize_email
  2. sanitize_file_name
  3. sanitize_html_class
  4. sanitize_key
  5. sanitize_meta
  6. sanitize_mime_type
  7. sanitize_option
  8. sanitize_sql_orderby
  9. sanitize_text_field
  10. sanitize_title
  11. sanitize_title_for_query
  12. sanitize_title_with_dashes
  13. sanitize_user

At this point, don't forget utilities such as regular expressions. They are incredibly powerful with matching only certain strings and certain patterns from a collection of data that can be extracted to save the data.


This Is Only Half of It

Granted, we've only talked about how to save information to the WordPress database.

We've yet to actually hit on how to retrieve information, let alone how to actually validate the information coming out of the database.

So in the next article, we're going to take a look how the flip side of this article - specifically, we're going to look at how to get information from the database, escape any potential characters that are potentially problematic with rendering them to the browser, and how to handle that.

Advertisement