phpzend-frameworkzend-dbzend-db-select

Securing my zend_db_select insert statement


I am using zend_db_select class as my sql wrapper. I would like to know if the following insert statement is secured. (whether it provide mechanism to prevent sql injection etc)

function createNew($message,$tags,$userid,$imgsrc){
    $data = array('message' => $message,
                      'tags' => $tags,
                      'imgsrc' => $imgsrc,
                      'createdtimestamp'=>new Zend_Db_Expr('NOW()'),
                      'userid' => $userid);   
    $this->dbo->insert('data', $data);
    return $this->dbo->lastInsertId();
}

I tried insert a row into the table with some quotes, and it didnt get escaped with \ , am i worrying too much or does phpmyadmin auto removed the \ for easy viewing? Confused. I read somewhere that zend_db_select caters for sql injection stuffs like that.

Advice appreciated. thanks


Solution

  • Yes, this is secure. Zend DB uses prepared statements, so each of the values of your array are automatically escaped using the appropriate mechanism.

    If you view the contents of your database (e.g. with a tool like phpMyAdmin), you should never see escaped quotes in there, this is the point of escaping data. If you insert the string O'Reilly, that's what ends up in your DB.

    Edit: Consider this query:

    INSERT INTO users (name) VALUES ('John O'Reilly')
    

    this won't work and will give you an SQL syntax error, because the SQL parser will see the second ' as the end of the column value, and will then choke when it sees the character following. So you escape need to escape that quote:

    INSERT INTO users (name) VALUES ('John O\'Reilly')
    

    The backslash tells it to treat the apostrophe following as a literal (i.e. don't treat it as the end of the column value). The backslash itself is never inserted into the database. This is an escape character, which is a common practice in computing.