in reply to drawbacks to 'eval' parameters/placeholders/binding in DBI calls to mysql database

Drawback: ever having a special character in the key name. Heaven forbid you end up with a key name with a single quote in it. (Which then leads to Bobby Tables problems.) Granted, that might cause other SQL problems, but in the general case, it's not unreasonable.

Just push each value into an array, and pass that in. Cheaper, easier to read, easier to maintain, easier to modify (grep, map, whatever), faster, fewer exploits/hard-to-find bugs. There's a reason why we say eval STRING is evil. It's rare that it's the right tool for the job, but it so easily can fit into so many jobs.

  • Comment on Re: drawbacks to 'eval' parameters/placeholders/binding in DBI calls to mysql database

Replies are listed 'Best First'.
Re^2: drawbacks to 'eval' parameters/placeholders/binding in DBI calls to mysql database
by ikegami (Patriarch) on Aug 20, 2009 at 22:24 UTC

    The solution is the appropriate use of quotemeta (aka \Q..\E) for eval and $dbh->quote_identifier for prepare.

    The OP's code is needless complicated as JavaFan pointed out, so I'll apply the solution to his code:

    my %memberRecord = ...; my @cols = keys %memberRecord; my @vals = values %memberRecord; my $stmt = do { local $" = ", "; my @q_cols = map $dbh->quote_identifier($_), @cols; my @params = ('?') x @cols; "INSERT INTO $tableName (@q_cols) VALUES (@params)" }; my $sth = $dbh->prepare($stmt); $sth->execute(@vals);
      Thanks. A quick test confirms that at least a single quote in a column name is covered with the proposed fix. I will investigate more, but I think I'm on the right track now thanks to all.
Re^2: drawbacks to 'eval' parameters/placeholders/binding in DBI calls to mysql database
by nextguru (Scribe) on Aug 20, 2009 at 22:39 UTC
    Thanks for the info. I was uniformed about the 'eval STRING' being evil, will have to research a bit more.