in reply to How hashes present keys and values.

To confirm what everyone else has said: yes, keys and values are promised to be consistent as long as you alter nothing about the hash

But no-one pointed out that if you're using DBI, you should not be constructing SQL with arbitrary values like that. You should be using placeholders. What if someone hands you a value with don't in it?

-- Randal L. Schwartz, Perl hacker

  • Comment on Re: How hashes present keys and values.

Replies are listed 'Best First'.
Re: Re: How hashes present keys and values.
by boo_radley (Parson) on Dec 13, 2000 at 19:05 UTC
    Excellent point, o-sensei merlyn. Error/ value checking will occur at a different place in the script -- no unsafe value should reach this sub.
    update
    for those of you wondering, an apostrophe will stun most SQL parsers. The short answer is something like
    s/'/''/g
      Or, a short answer that works is something more like:
      $quoted = $dbh->quote($raw);

      But it's much better to use the placeholders, as they can be trained in the SQL datatypes so as to quote correctly for those DBDs that have specific needs.

      -- Randal L. Schwartz, Perl hacker

        OK, so, to do it right, I'd want :
        sub create_SQLprepared{ my ($l_database, $l_tablename,@l_fields) = @_; my $l_fieldnames; my $l_placeholder; my $l_statement; my $l_fieldnames = join ",", (@l_fields); foreach (@l_fields) {$l_placeholder .= "?"} $l_placeholder = (join ",", (split //, $l_placeholder)); print "INSERT $l_tablename (" . $l_fieldnames . ")\n VALUES (" . $ +l_placeholder . ")"; $l_statement = $l_database->prepare("INSERT $l_tablename (" . $l_f +ieldnames . ")\n VALUES (" . $l_placeholder . ")"; return (\$l_prepare); }
        ? Where $l_database is a reference to a database handle, $l_tablename is a string, and @l_fields is a list of field names for the insert. Returns a reference to the statement handle.
        It is not always possible to use placeholders with insert statements (Sybase and MS SQL server come to mind as not implementing these yet for anything other than a select), so you need to use $dbh->quote() in these cases, or if you want to be comaptible across a number of types of databases.