Search code examples
mysqlzend-frameworkzend-dbzend-db-table

Set a value to null, when calling Zend_Db::update() and insert()


My question is the exact same as How to Set a Value to NULL when using Zend_Db

However, the solution given in that question is not working for me. My code looks like the following. I call updateOper on the Model class when update is clicked on the front end. Inside updateOper, I call another function trimData() where I first trim all whitespace and then I also check that if some of the fields are coming in empty or '' I want to set them to default values or NULL values. Therefore I am using new Zend_db_expr('null') and new Zend_db_expr('default') .

The code is as follows:

private function trimData(&$data ) {

    //Trim whitespace characters from incoming data.
    foreach($data as $key => $val)
    { 
        $data[$key] = trim($val);
        if($data['notes'] == '') {
            error_log("set notes to null/default value");
            $data['notes'] = new Zend_db_expr('DEFAULT');
        }
    }

}

public function updateOper($data, $id)
{
    $result = 0;

    $tData = $this->trimData($data);

    error_log("going to add data as ".print_r($data, true));
    $where = $this->getAdapter()->quoteInto('id = ?', $id);
    $result = $this->update($data, $where);

    return $result;
}

The error_log statement prints the $data array as follows:

[id] => 10    
[name] => alpha
[notes] => DEFAULT

As a result, the notes column has value ='DEFAULT' instead of picking the default value given in the table definition.

I have been trying to figure out what is wrong, but have not been able to find a solution. I would really appreciate your help.

Thanks so much!


Solution

  • Your $data['notes'] is being changed to the __toString() value of the Zend_Db_Expr instead of preserving the actual object.

    Maybe the reference is clogging things up. Else you may need to move the expression declaration into the actual update query.