Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass MySQL functions as bind parameters in prepared statement?

Tags:

mysql

bind

perl

dbi

I'm trying to do this:

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

without any luck. Any ideas?

like image 875
aidan Avatar asked Feb 09 '10 16:02

aidan


People also ask

How do you bind a parameter in SQL?

Bind parameters—also called dynamic parameters or bind variables—are an alternative way to pass data to the database. Instead of putting the values directly into the SQL statement, you just use a placeholder like ? , :name or @name and provide the actual values using a separate API call.

Does MySQL support prepared statements?

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency and protect against SQL injections. The prepared statement execution consists of two stages: prepare and execute.

How do I run a prepared statement in MySQL?

EXECUTE the PREPARED statementEXECUTE stmt USING @variable_name; Here @variable_name will have the value which we want tp pass at the place of ? in the PREPARE statement. We need to set the value of @variable_name by using SET statement before executing the prepared statement.

Is SQL injection possible with prepared statements?

Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.


3 Answers

$sth = $dbi->prepare('INSERT INTO table VALUES (?, COALESCE(?, NOW()), ?)');
$sth->execute(
    $var1,
    $var2,
    $var3
);
like image 147
Quassnoi Avatar answered Oct 13 '22 00:10

Quassnoi


Functions cannot be bound parameters. MySQL will enclose them in quotes which is not valid syntax.

Your options are:

  • DEFAULT CURRENT_TIMESTAMP - If the field is a TIMESTAMP field you can declare it to have a default of the current time like this. This does not work for DATETIME fields.
  • Use perl - $now = time2str('%Y-%m-%d %T', time);
like image 25
hobodave Avatar answered Oct 13 '22 00:10

hobodave


You can use the following coding also.

$sth = $dbi->prepare('INSERT INTO table VALUES (?, COALESCE(?, NOW()), ?)');
$sth->bind_param($var1,$var2,$var3); 
$sth1=$sth->execute;
like image 31
muruga Avatar answered Oct 13 '22 01:10

muruga