If the user didn't enter anything for 'blah', how do I create the sql statement so that it will populate the field with 'NA'?

Sadly, when you prepare an insert statement with a particular set of fields using placeholders, the "default" value for a given field in the mysql table definition will never be applied, ever -- even when the associated variable is undef.

To handle that in a way that does not require database details to be embedded in your perl script, you have to use a flexible method of preparing the statement, so that you can leave out fields when their associated values are empty:

sub add_foo { my @expected_fields = qw/bar blah/; my ( @insert_flds, @insert_vals ); for my $f ( @expected_fields ) { my $v = shift; next unless ( defined( $v ) and length( $v )); push @insert_flds, $f; push @insert_vals, $v; } my $sth = $dbh->prepare_cached( 'insert into foo (' . join( ',', @insert_flds ) . ') values (' . join( ',', ('?') x @insert_flds ) . ')' ); $sth->execute( @insert_vals ); return $dbh->last_insert_id( undef, undef, 'foo_id' )); }
(that assumes use of RaiseError => 1 in the DBI->connect call to handle error checking).

In reply to Re: Using MySQL table's default values upon insert by graff
in thread Using MySQL table's default values upon insert by Zettai

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.