views:

45

answers:

2

Wordpress ships with the wpdb class which handles CRUD operations. The two methods of this class that I'm interested in are the insert() (the C in CRUD) and update() (the U in CRUD).

A problem arises when I want to insert a NULL into a mysql database column - the wpdb class escapes PHP null variables to empty strings. How can I tell Wordpress to use an actual MySQL NULL instead of a MySQL string?

A: 

I don't think wordpress intends for you to be micromanaging their database calls. They have a number of (more or less) convenient abstraction layers between the database and the application, and If you are using those and worrying about how they store the data then either there's a problem with the abstractions (where you should be doing all your work) or your familiarity with them. But their paradigm works pretty well for a lot of people the way it is.

Is there a particular problem you are trying to solve where their way of handling it (which might not have been yours or mine if we had designed it) doesn't work as they intended it to?

le dorfier
The `insert()` and `update()` functions can be used by Wordpress plugin writers (such as myself) to manage rows in custom, plugin-specific tables. I'm looking for a way to tell Wordpress to insert NULLs aside from generating the SQL statement strings myself. (And let the Wordpress core take care of SQL as much as possible, without creating redundant classes on my end).
pygorex1
+1  A: 

If you want it to compatible you would have to SHOW COLUMN and determine ahead if NULL is allowed. If it was allowed then if the value was empty($v) use val = NULL in the query.

$foo = null;
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";

if ($foo == null) {
$wpdb->query( $wpdb->prepare( "
    INSERT INTO $wpdb->postmeta
    ( post_id, meta_key, meta_value, field_with_null )
    VALUES ( %d, %s, %s, NULL )", 
        10, $metakey, $metavalue ) );
} else {
$wpdb->query( $wpdb->prepare( "
    INSERT INTO $wpdb->postmeta
    ( post_id, meta_key, meta_value, field_with_null )
    VALUES ( %d, %s, %s, %s)", 
        10, $metakey, $metavalue, $foo ) );
}
Brant
I created the tables as part of a custom plugin - the columns in question do accept NULL values.
pygorex1
@pygorex1 - How's this?
Brant
This is pretty much the only solution aside from changing the NULL/empty semantics of my plugin.
pygorex1
@pygorex1 - Thanks for the accept.
Brant