Andrew Gaffney wrote:
I have a Perl CGI script that runs a query against a MySQL table. I have about 20 boolean values that I want shown as checkboxes in the produced HTML, but I don't want to have to do something like the below for every value.


The key to this is contriving good names for the check boxes, usually such that they can be looped over...


[code]
if($ref->{somevalue}) {
  print "<input type=checkbox name=somevalue value=1 checked>";
} else {
  print "<input type=checkbox name=somevalue value=1>";
}
[/code]


foreach my $index (1 .. 20) {
print "<input type=checkbox name=somevalue$index " . ($ref->{"somevalue$index"} ? ' checked=checked' : '') . ">";
}


The (exp ? string : string) is called the ternary operator, perldoc perlop for more.

Converting back is easy enough:

[code]
use CGI;
my $cgi = new CGI;
my $p = $cgi->Params;

$somevalue = $p->{somevalue} or $somevalue = 0;
[/code]

If it was checked, it will be passed along with a value of 1. If it's not checked, it won't be passed along and will return undef if I try to grab it from the $p hash. Although, how could I quickly convert all the values back for something like:

[code]
$dbh->do("UPDATE table SET somevalue1='$p->{somevalue1}', somevalue2='$p->{somevalue2}', somevalue3='$p->{somevalue3}', somevalue4='$p->{somevalue4}', somevalue5='$p->{somevalue5}', somevalue6='$p->{somevalue6}'");
[/code]



Generally what I do is break up the statement, so


my @bind;
my $set = '';
foreach my $index (1 .. 20) {
  if (defined $p->{"somevalue$index"}) {
      $set .= ', ' if ($set ne '');
      $set .= '?';
      push @bind, $p->{"somevalue$index"};
  }
}

my $st = "UPDATE table SET $set";

Now you have constructed your update statement, pass it and the bind variables to a prepare/execute ('do' might work too) but binding variables works really well here (and for any other fields that may need to be apostrophe escaped, etc.).

Would MySQL choke if it was expecting a non-null integer value for all of those? If so, how can I handle that without a lot of code? I currently handle the data both ways by having a textfield with a '1' or '0' in the generated HTML, but it looks ugly.


Depends on the table definition. If you have fields marked as NOT NULL then it might since it won't like NULL values, though empty strings are not NULLs. Alternatively set a default value in the table definition, for instance I use 0 for off usually, anything that I am not checking NULLs against I automatically have initialized to 0.


I am not entirely sure I understood what you are after, if this didn't get it please clarify and I (we) will see what we can come up with...

http://danconia.org

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to