Search code examples
phpmysqlzend-frameworkpdozend-db

Zend_Db_Statement_Pdo->execute with expression in params


I try to execute insert statement with "on duplicate" part. As I know Zend doesn`t support this, so I use simple statement:

$sql = "INSERT INTO agent(`inn`, `name`, `created`) VALUES(:inn, :name, :created) ON      
DUPLICATE KEY UPDATE `inn` = :inn, `name` = :name, `created` = :created";
$stmt = $this->db->prepare($sql);
$stmt->execute($bind);

Where $bind - is array:

array(
  'inn'=>1234567890,
  'name'=>'test user', 
  'created' = new Zend_Db_Expr('NOW()')
);

If I try this query through phpMyAdmin - all works fine, but after script execution the "created" column value is '0000-00-00 00:00:00'.

WTF?


Solution

  • You can't use an expression as an argument to a placeholder in a prepared statement. It will be interpreted as a string. This has nothing to do with zend framework.

    You can either created a formatted date string in php and use that, or use now() in the prepared statement like

     VALUES(:inn, :name, NOW())
    

    Another solution, if you need to sometimes supply a datetime, and sometimes use NOW(), is using conditionals to check for that specific case

     VALUES(:inn, :name, IF(:created = 'NOW()', NOW(), :created))