
Continuing on with our mini-series on the WordPress Database class, today we’ll be talking about using the class to insert and update data in the database. The WPDB class makes this super simple, no SQL queries required.
Inserting Data
Using the WPDB class, you can insert an array of data into a table in the database. The syntax of this function is simple:
[code='php']$wpdb->insert( $table, $data );[/code]
$table is the name of the table you want to insert the data into and $data is an array of field names and data you want added to $table. For the data array, the field name should be the key, while the value should be the data for that field name. So, if we (for example purposes) wanted to use this function to add an option to the options table, we we do so like this:
[code='php']$data_array = array('option_name' => 'example_option',
'option_value' => 'This is an example option!');
$wpdb->insert( $wpdb->prefix . 'options', $data_array );[/code]
Which would add a new row in the options table, with an option_name of example_option and an option_value of This is an example option!. You only need to specify the field names that you would like data added to. $data should not be escaped first. Obviously, we could accomplish the same result much easier using add_option, but this is simply for example purposes.
Notice the $wpdb->prefix part. Because it is possible to set WordPress up with a prefix different from wp_, it is good programming practice to always use $wpdb->prefix for the prefix in table names.
Updating Data
If you want to update an existing row in the database, we can use a WPDB function for this. This function is almost the same as insert, but it also allows you to specify the WHERE clause. Thus, the syntax is:
[code='php']$wpdb->update( $table, $data, $where );[/code]
The $table and $data values are the same as in the insert function. $where is an array where the keys are column names and the values are what their values should be; therefore creating the WHERE clause. So, if we wanted to update our example option from above, we could do this:
[code='php']$data_array = array('option_value' => 'This is a *new* example option!');
$where_array = array('option_name' => 'example_option');
$wpdb->update( $wpdb->prefix . 'options', $data_array, $where_array );[/code]
Which would update any row whose option_name is example_option, in the options table, with the new value for option_value. Again, $data should not be escaped before hand.
To conclude
This concludes our mini-series on the WordPress Database class. If you have any questions, feel free to ask them in the comments.


