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?
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.
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.
The global $wpdb variable is more powerful than the get_option() function as it allows you to manipulate and retrieve data from any table in wordpress, including all plugin tables. This gives you more power than simply gaining access to the options table.
WPDB reference
You should use get_option() when you are specifically retrieving an option from the options table, used for plugin options. Other variations of this function are add_option, update_option, and delete_option. All of the related functions should be used specifically for plugin options.
I've used both before. If you can use the helper functions, you should do so. If you need to do something very custom you can use the global. I only use the global if I just must write my own query
I use both in my development.
get_option() is far easier for static or single info bites
$wpdb is better for storing multi-dimensional information
The primary difference is that for grab-and-go information (like license keys, expiration dates, and static info) get_option() is really handy. It's trim, fast, and really easy to use.
But, I develop plugins that manage user data and form submissions, and in cases like this get_option() doesn't offer the versatility I need without writing a lot of compound arrays or trying to track multiple options. For multi-dimensional information, or for cross-referencing related data entries for a plugin, $wpdb is much better - you can structure your own tables and sort/organize how you like.
:)
Related
I am developing a plugin in WordPress that is about to store configurable entities. They are jobs to be done by Cron. There are plenty of them and each one has name, frequency and some additional data.
There are discussions how to store post-related data in plugins, whether to use postmeta table or own tables. It is officially adviced to use postmeta whenever possible. But what if those entities are not posts? I have 3 possibilities:
Use separate table(s) to store them
Use options table
Make those entities posts with custom post type
I used to keep this kind of information in options table, but how would you do that?
Basically, when you are trying to decide if you need a custom table or not, answer a simple question: does my data need indexes and fast searching? If yes - go with custom tables. If not - e.g.:
this data is being read from database with the post itself - use postmeta
this data is used rarely and is called directly by keys - use options
Else, if you need to store a lot of structured data, perform selects, sorts, or even joins etc - custom db table is your option. Read the docs and do it using core functions and features, like db_delta() function etc. There's nothing wrong in using custom db tables. Just do it right, the "WordPress way".
I have a form that a user will enter their studentID,Name,Major etc. then use those info to fill up 'student' class to create a 'student' object.
Now, I want to store these objects somewhere, somehow, and I want to be able to pull them back to use its data. I've looked into 'object serialization' but not quite sure if this will fulfill my needs, as I don't fully understand how this thing works...any help would be great, thanks.
And, I don't want to create a database, at all. No Mysql is allowed for this little assignment of mine...
You could serialize your object as is and persist it to disk, but what happens if you want to search for students based on some criteria?
Usually, a relational database is used and an ORM to map your PHP objects to a rdbms table
Wikipedia has a list of ORM's and frameworks for PHP, If you want something more lightweight then managin a db server, at least look into Sqlite
Be careful when storing serialize objects. You might loose the ability to do certain things like search records. And if you don't understand how they work then they might behave unexpectedly.
A better approach would be to store individual properties as rows in database tables and then fetch the data into objects. To do this you can use ORMs like Doctrine which will map objects to database tables and persist them. Or a simple database class using PDO should fulfill your basic needs as well.
I was wondering how does you guys write your classes when they need tables in the database to function or some other things to do before it functions?
Do you use a method to insert the tables in the database or do you write the class to require some columns in a table which can be define at some settings variable?
Whilst the answer to this question is a matter of opinion, I would generally create them in the class constructor (checking whether they exist first or not), however I would allow the user to specify their own names and prefixes to avoid clashes and data loss within their database.
The reason being is that you have total control over how the tables are constructed as opposed to trusting the user to generate them correctly.
This is assuming your class will be used by other people, if it is solely for your own use it is safe enough to assume you are able to build the tables yourself and could remove that overhead from the class.
It also depends what your class is for, if it is a plugin then you should definitely create these for the user so they don't have to touch the underlying code, following any of the database naming conventions of the system your plugin is integrating with.
This is just my personal style and is by no means a standard or necessarily the optimum way.
I am trying to store an object in a column on one of my tables, its sort of a settings logic, but I am in the process of conforming my older styling of mysql_query() style querys into the active record methods. Of which I am now getting a
"Duplicate Entry" for PRIMARY
as an error from the DB Class, and the only thing I can associate it with is, the fact that I am attempting to pass this object which is being escaped, and I think its breaking the insert/update query
Sure, just use json_decode() (http://www.php.net/json_decode) and make sure it will be conform to the table-rows. Use typecasting if needed to force certain values to be correct.
json_encode() will store your JSON string to a native PHP Array, thus making it easy to work with it from there to format it into your DB Table's format.
If you add some code to your questions, I can probably give you a more detailed answer.
I'm currently at an impasse in reguards to the structural design of my website. At the moment I'm using objects to simplify the structure of my site (I have a person object, a party object, a position object, etc...) and in theory each of these is a row from it's respective table in the database.
Now from what I've learnt, OO Design is good for keeping things simple and easy to use/implement, which I agree with - it makes my code look so much cleaner and easier to maintain, but what I'm confused about is how I go about linking my objects to the database.
Let's say there is a person page. I create a person object, which equals one mysql query (which is reasonable), but then that person might have multiple positions which I need to fetch and display on a single page.
What I am currently doing is using a method called getPositions from the person object which gets the data from mysql and creates a separate position object for each row, passing in the data as an array. That keeps the queries down to a minimum (2 to a page) but it seems like a horrible implementation and to me, breaks the rules of object orientated design (should I want to change a mysql row, I'd need to change it in multiple places) but the alternative is worse.
In this case the alternative is just getting the ID's that I need and then creating separate positions, passing in the ID which then goes on to getting the row from the database in the constructor. If you have 20 positions per page, it can quickly add up and I've read about how much Wordpress is criticised for it's high number of queries per page and it's CPU usage. The other thing I'll need to consider in this case is sorting, and doing it this way means I'll need to sort the data using PHP, which surely can't be as efficient as natively doing it in mysql.
Of course, pages will be (and can be) cached, but to me, this seems almost like cheating for poorly built applications. In this case, what is the correct solution?
The way you're doing it now is at least on the right track. Having an array in the parent object with references to the children is basically how the data is represented in the database.
I'm not completely sure from your question if you're storing the children as references in the parent's array, but you should be and that's how PHP should store them by default. If you also use a singleton pattern for your objects that are pulled from the database, you should never need to modify multiple objects to change one row as you suggest in your question.
You should probably also create multiple constructors for your objects (using static methods that return new instances) so you can create them from their ID and have them pull the data or just create them from data you already have. The latter case would be used when you're creating children; you can have the parent pull all of the data for its children and create all of them using only one query. Getting a child from its ID will probably be used somewhere else so its good just to have if its needed.
For sorting, you could create additional private (or public if you want) arrays that have the children sorted in a particular way with references to the same objects the main array references.