Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to set empty vars to NULL?

Hi,

I searched the web hours for this but now I have to ask.

How can I set values to NULL if there are empty? When I try to execute

$form->create();

I get the error "Exception: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'heartrate' at row 1" because heartrate is an empty string. How can I set it automatically to NULL?



7.2k

Just, for example,

$str = '';

echo (int)$str;

String conversion



4.3k

Just, for example,

```php $str = '';

echo (int)$str; ```

String conversion

This will lead to zeros in my database. I need NULLs.



46.5k
Accepted
answer
edited Jun '16

This is what I use for my custom models.

  //removes all NULL, FALSE and empty strings but leaves 0 (zero) values
            $buffer = array_filter($modelData, 'strlen');   //$modelData is an array


4.3k

This is what I use for my custom models.

```php //removes all NULL, FALSE and empty strings but leaves 0 (zero) values $buffer = array_filter($modelData, 'strlen'); //$modelData is an array ```

That looks promising. Where do you get $modelData from?

It's out of scope of this topic (like I said, custom Models/ORM implementation).

You should focus on array_filter like I provided in example.