How to pass MySQL functions as binding parameters in a prepared statement?

I am trying to do this:

$sth = $dbi->prepare('INSERT INTO table VALUES (?, ?, ?)'); $sth->execute( $var1, $var2 || 'NOW()', $var3 ); 

no luck. Any ideas?

+7
mysql perl dbi bind
source share
3 answers
 $sth = $dbi->prepare('INSERT INTO table VALUES (?, COALESCE(?, NOW()), ?)'); $sth->execute( $var1, $var2, $var3 ); 
+14
source share

Functions cannot be related parameters. MySQL will enclose them in quotation marks, which is not a valid syntax.

Your options:

  • DEFAULT CURRENT_TIMESTAMP. If the field is a TIMESTAMP field, you can declare that it has a default value for the current time like this. This does not work for DATETIME fields.
  • Use perl - $now = time2str('%Y-%m-%d %T', time);
+3
source share

You can also use the following encoding.

 $sth = $dbi->prepare('INSERT INTO table VALUES (?, COALESCE(?, NOW()), ?)'); $sth->bind_param($var1,$var2,$var3); $sth1=$sth->execute; 
+2
source share

All Articles