Wordpress Database $wpdb versus get_option()
So I have been developing plugins that create interact and delete to a database by using the get_option functions.
I have now seen some tutorials showing how to use the global $wpdb way of getting values from the database.
What is the difference between the two, and is one better than the other?
Using WordPress helper functions (not limited to get_option()) will ensure your plug in to be forward compaitable when newer version of WordPress made changes that may potentially effect your code.
You are recommanded to understand and use their helpers before considering coding your own.
For storing plugin options or light weight data related to posts, get_option(), get_post_meta(), and their related functions are ideal. For relational database activity, $wpdb is best choice. Here's why:
$wpdb is a class based on the ezSQL PHP class for interacting with the database. Some features include:
1) provides SQL injection protection using the $wpdb->prepare(), $wpdb->insert(), and $wpdb->update() methods. get_option() is a helper function that allows you to do a Key => Value pair.
2) $wpdb is easy to use. It can return record sets in various forms: $wpdb->get_results($sql, ARRAY_A) an Array or Associative Arrays containing the returned rows with the column names being the keys. $wpdb->get_results($sql) would return an array of object with the column name as properties of the object. $wpdb->get_var($sql) would return a scalar result (the first column of the first row of the data set from the query). $wpdb->get_row($sql) would return a single row as an object.
3) $wpdb allows you to interact with any table in the database, even performing free form queries using $wpdb->query($sql)
4) WordPress will likely insure that your interactions with $wpdb will not need to change if they add support for databases other than MySQL. The original ezSQL class was intended to provide some cross database support.
So, if you're needing to deal with data in a relational way, $wpdb is really an excellent choice for WordPress.
get_option() and get_post_meta() provide an easy way of dealing with small amounts of data, either relating to a specific post in the case of get_post_meta() or as a Key => Value pair with get_option().
One of the nice things about these is that you can save a serialized array or object and get that data back out as either an array or object. This gives you a very easy way to deal with fields of data as if you had a database table. However, this doesn't work well if you need to relate data between tables or do summing, counting, or other database calculations on the serialized data. I those cases, a fully fledged table and $wpdb would better serve.