in reply to Array values into a database help!

You can either adjust the values or adjust the query.

Three ways to adjust the values:

my $sth = $dbh_in->prepare(" INSERT INTO my_table ( name_1, name_2, name_3, name_4 ) VALUES ( ?,?,?,? ) "); $sth->execute($fields[0], $fields[1], $fields[2], $fields[3]); $sth->execute(@fields[0..3]); $sth->execute((@fields, undef, undef, undef, undef)[0..3]);

One way to adjust the query:

my $sth = $dbh_in->prepare(" INSERT INTO my_table ( " . join(', ', map 'name_'.$_, 1..@fields) ." ) VALUES ( " . join(',', ('?') x @fields) ." ) "); $sth->execute(@fields);

(I'm assuming WHERE user=... shouldn't be there? If it is, be sure to use a placeholder for that too!!!)

Update: Added more ways of adjusting the values.

Replies are listed 'Best First'.
Re^2: Array values into a database help!
by Anonymous Monk on Nov 28, 2010 at 05:13 UTC
    On this line:
    $sth->execute((@fields, undef, undef, undef, undef)[0..3], $user);
    If any of the 4 values are not true it will send a null/empty value to the database, or if some are true, it will send that value. else the rest will be null/empty, right? If its yes, thank you!!
      Exactly, although I've added simpler alternatives to the list slice to my original post. The list slice approach is useful if you want a default of something other than undef (NULL).
Re^2: Array values into a database help!
by Anonymous Monk on Nov 29, 2010 at 00:52 UTC
    How would this code work with an SQL UPDATE instead of an INSERT?
      Identically.