I have a query that I wrote some time ago looking something like this:
$script = 'SELECT foo FROM bar WHERE item1 = ' . $item1; if(defined($item2)) { $script .= ' and item2 = ' . $item2; } if(defined($item3)) { $script .= ' and item3 = ' . $item3; }
Having some time lately to go revisit this (and being smart enough these days to want to do better), I would like to something more like this:
$script = 'SELECT foo FROM bar WHERE item1 = ?'; if(defined($item2)) { $script .= ' and item2 = ?'; if(defined($item3)) { $script .= ' and item2 = ?';
so that I could do something like this:
$sql->execute($item1,$item2,$item3);
Does DBI support this kind of behavior? Can I pass additional items to execute() even if there are no placeholders that correspond with them? How will DBI react if those items are undefined? SuperSearch yielded nothing, and I couldn't find what I was looking for in the DBI reference. While the DBI docs that you can't pass an undef value to a SELECT statement via a placeholder and expect to get the results you are looking for (that just strikes me as poor programming and a bad idea anyhow), that's not exactly the same as what I'm trying to accomplish.

Any insight is truly appreciated.

Thanks in advance,
MrCromeDome


In reply to Varying numbers of DBI placeholders by MrCromeDome

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.