I usually do this like so:
"SELECT FROM table WHERE ". ( $form_username ? "username = $form_username " : '' ). ( $form_username && $form_password ? 'AND ' : '' ). ( $form_password ? "password = $form_password " : '' ). ( ($form_username || $form_password) && $form_name ? 'AND ' : '' ) +. ( $form_name ? "name = $form_name" : '' );
It's not really any shorter than your if-statement version, but my brain finds it easier to read. If you have a number of statements like this, you can write a little sub to generate them. The sub could use a loop, or it could use a variation of the concatenation statement above, for which the general form is:
a (or not) AND if a and b b (or not) AND if (a or b) and c c (or not) AND if (a or b or c) and d ... z (or not)
Here's a sub using a loop:
$sql_string = make_anded_statement ( username => $form_username, password => $form_password, name => $form_name ); sub make_anded_statement { my ( %args ) = @_; my @keys = keys %args; my $where_string = ''; my $ANDING = 0; foreach my $i ( 0 .. $#keys ) { if ( $args{$keys[$i]} ) { $where_string .= $keys[$i] . '=' . $args{$keys[$i]} . ' '; $ANDING = 1; } if ( $ANDING && $args{$keys[$i+1]} ) { $where_string .= 'AND '; } } return "SELECT FROM table WHERE $where_string"; }

In reply to Re: mysql search statement by khkramer
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.