简体   繁体   中英

Make MySQL default to a NULL when an enum field is set to an invalid value

Is there a way to make MySQL default to a NULL when an enum field is set to an invalid value?

Also, is there a way I can specify a value in an HTML form such that, when saved to the DB, it stores as a NULL. I don't want to do any checks like "if empty string, then save a NULL." If it's possible, is it a good idea? Any security concerns?

My scenario: I have an HTML drop down menu that has an "null" option followed by a list of items that correspond to the DB's enum. When the null option is selected and saved, I want it to reflect as a NULL in the DB. Right now, it's being converted to an empty string, as per:

If you insert an invalid value into an ENUM (that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value. This string can be distinguished from a “normal” empty string by the fact that this string has the numeric value 0.

http://dev.mysql.com/doc/refman/5.5/en/enum.html

" If an ENUM column is declared to permit NULL, the NULL value is a valid value for the column, and the default value is NULL. If an ENUM column is declared NOT NULL, its default value is the first element of the list of permitted values. "

On this basis, if you don't set a value for the field with your INSERT statement and you have declared the ENUM field to accept NULL, it will default to NULL.

[EDIT]

To address your comment, if you have this table definition

CREATE TABLE IF NOT EXISTS `tbl_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` enum('New','Done') DEFAULT NULL,
  PRIMARY KEY (`id`)
)

And your web application is attempting to UPDATE and existing record using something like this

UPDATE `test`.`tbl_test` SET `type` = NULL WHERE `tbl_test`.`id` =1

It will set the value to NULL.

You can reduce the risk of invalid enum data appearing in your HMTL drop downs by querying the table for the possible ENUM values to dipaly in the drop down. Here's a Php example I found

SHOW COLUMNS FROM `tbl_test` WHERE Field = 'type'

[EDIT]

To answer your additional comment, if you want the user to be able to select a NULL value and also allow an empty string as a valid value you need to sepecify your drop down like this

<select>
  <option value="-1">-- not selected ---</option>
  <option value=""></option>
  <option value="Book">Book</option>
  <option value="Music">Music</option>
</select>

By using the <option value= ...> attribute you can control the value POSTed to your WebApp and can then process accordingly. In this example a value of -1 would be translated to NULL by your WebApp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM