inquiring minds
inquiring minds

Reputation: 1915

Why can't I use mysql_real_escape_string with zend framework's update() method?

I'm having trouble with Zend Db's update() method. It's not safe against sql injection on its own.

Select methods seem safe, so I could theoretically do a select and then simply do a save() after modifying the fields I want to update. But, I don't want to have to run 2 queries - a select followed by an update, just to run an update. That doesn't seem efficient.

To solve this, I tried to use mysql_real_escape_string(), but it actually caused the data I was trying to update to got into the database as an empty string. Not sure why.

Here is the code:

public function updateMyTable($data,$id){
    $safeData=array();
    foreach($data as $field=>$val){
        $safeData[$field] = mysql_real_escape_string($val);
    }
    $where[]= 'id = '.mysql_real_escape_string($id);
    self::instance()->update($safeData,$where)
}

Does anyone know if I have something incorrect that is causing the blank database entry? Or, a way to safely use update()? I didn't want to use Zend's quote() method because it actually puts slashes into my data in the database. Thanks.

Upvotes: 1

Views: 3005

Answers (2)

Headshota
Headshota

Reputation: 21449

mysql_real_escape_string needs a connection to the database opened by mysql_connect to work, and if the framework uses another driver e.g. mysqli it will fail to escape the string with this function. look for the documentation, there should be a special method for escaping data within the framework.

Upvotes: 3

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22172

When you update a Model in Zend Framework you should write a code like this:

$Values = array(
   'Col1' => $this->Attr1,
   'Col2' => $this->Attr2
);

$RowChanged = $Db->update('table_name', $Values, $Db->quoteInto('Id = ?', $this->Id));

Upvotes: 3

Related Questions