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?
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.
Here’s a solution to your problem. In “wp-content” folder, create a file named “db.php” and put this code in it:
In this way you can use null values with wpdb!
I find this on WordPress StackExchange forum and it works very well for me.
and the function wp_db_null_value is:
Because in my case I cannot use $db->prepare() function…
wpdb
insert()
andupdate()
works withNULL
values, it was patched many years ago but never mentioned in the Codex.In your case:
Ref: https://core.trac.wordpress.org/ticket/15158#no0
I tried to edit one of the other solutions listed here, because it resulted in the format array being misaligned with the data array, but failed.
Here is a solution that modifies the wpdb from the latest version of wordpress, in order to allow inserting and updating null values into SQL tables using insert() and update():
Insert this code into somewhere that always gets run, like your functions.php, and then use your new global $wpdb_allowed_null->insert() and ->update() as normal.
I preferred this method vs. overriding the default $wpdb, in order to preserve the DB behavior that the rest of WordPress and other plugins will expect.