I used to use the standard mysql_connect(), mysql_query(), etc statements for doing MySQL stuff from PHP. Lately I’ve been switching over to using the wonderful MDB2 class. Along with it, I’m using prepared statements, so I don’t have to worry about escaping my input and SQL injection attacks.
However, there’s one problem I’m running into. I have a table with a few VARCHAR columns, that are specified as not-null (that is, do not allow NULL values). Using the old MySQL PHP commands, I could do things like this without any problem:
INSERT INTO mytable SET somevarchar = '';
Now, however, if I have a query like:
INSERT INTO mytable SET somevarchar = ?;
And then in PHP I have:
$value = ''; $prepared = $db->prepare($query, array('text')); $result = $prepared->execute($value);
This will throw the error ‘null value violates not-null constraint‘
As a temporary workaround, I check if $value is empty, and change it to ' ' (a single space), but that’s a horrible hack and might cause other issues.
How am I supposed to insert empty strings with prepared statements, without it trying to instead insert a NULL?
EDIT: It’s too big of a project to go through my entire codebase, find everywhere that uses an empty string ” and change it to use NULL instead. What I need to know is why standard MySQL queries treat ” and NULL as two separate things (as I think is correct), but prepared statements converts ” into NULL.
Note that ” and NULL are not the same thing. For Example, SELECT NULL = ''; returns NULL instead of 1 as you’d expect.
This sounds like a problem with the MDB2 API fumbling PHP’s duck typing semantics. Because the empty string in PHP is equivalent to NULL, MDB2 is probably mis-treating it as such. The ideal solution would be to find a workaround for it within it’s API, but I’m not overly familiar with it.
One thing that you should consider, though, is that an empty string in SQL is not a NULL value. You can insert them into rows declared ‘NOT NULL’ just fine:
If you’re unable to find (or implement) a workaround in the MDB2 API, one hackish solution (though slightly better than the one you’re currently using) might be to define a user variable for the empty string —
Finally, if you need to use the empty string in an INSERT statement but find yourself unable to, the default value for string types in MySQL is an empty string. So you could simply omit the column from INSERT statement and it would automatically get set to the empty string (provided the column has a NOT NULL constraint).