Use join:
my $sql ='select from table where' . join(' and ', ( " username = $form_username", "password = $form_password", "name = $form_name", ) );

Update: listen to talexb. This really is something you should let the database handle. Alternatively, I would recommend just using your code and take out the last AND ... sure it isn't elegant, but, if and only if you have a few form variables, well, it does get the job done.

I have been toying with hash to solve this problem, but it's tricky, mainly because undef is slightly different than the empty string ... which is something you have to consider with this problem. My idea is to have the database column names as the keys, and the form variables as the values - if i can find a convienient way to remove all keys whose values are undefined or empty strings, then creating the SQL statement will be a sinch ... back in a few ...

Okay, here it is - i doubt i'll ever use, but it was fun anyways ;)

my %hash = ( username => $form_username, password => $form_password, name => $form_name, ); # was trying to do this with map ... but time is short ;) for (keys %hash) { delete $hash{$_} unless $hash{$_}; } my $sql = 'select from table where ' . join(' and ', map { qq|$_ = "$hash{$_}"| } keys %hash);
Hope this helps somehow - check out Coding Errror for more info (like bind vars).

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)

In reply to (jeffa) Re: mysql search statement by jeffa
in thread mysql search statement by Parham

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.