douyi1084 2015-12-26 15:49
浏览 227
已采纳

使用JQuery Serialize时如何为空白字段插入NULL值?

I have many forms that I am serializing. The data is posted to either an insert.php page or update.php.

If a form input is left blank, I want to insert a NULL value into my database. I'm using mySQL.

It seems like when a form is serialized, any fields that are left blank are sent as value of '' which does NOT insert as NULL into my db.

I can filter out empty inputs before serializing, but this isn't good when a record needs to be updated.

Here's a fiddle of a form that you can at least see that empty inputs are logged as "".

Any advice on how I can set those values to NULL instead?

jsfiddle.net/gabrieleromanato/bynaK/

  • 写回答

1条回答 默认 最新

  • doujian1050 2015-12-26 15:57
    关注

    You can simply at php side check if value is empty use instead null with strlen(...) == 0 condition ( as @PaulSpiegel mentioned in comment of this answer empty will consider that 0 is also empty and will write null to your db ) - http://php.net/manual/en/function.strlen.php

    // Example
    $value = !strlen($_POST['value']) ? null:$_POST['value'];
    // .. save in MySQL 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?