Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

sql select with array

by Anonymous Monk
on Oct 22, 2001 at 13:22 UTC ( [id://120473]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How can I use SELECT with my list "@selector". I can only get it to work when I write "$selector[[0]]" ect. What is wrong with my code?????

BR Soren

***********************CODE***********************
my @selector; if ($rapport eq undef) { @selector = qw(fornavn efternavn cpr adresse zip city telefon mobil g_afsluttet bemyndigelse_til tjenestested id pic); } else { @selector = qw(fornavn efternavn cpr bemyndigelse_til <br>tjenestested +); } my $row = $dbh->selectall_arrayref("select @selector from people where (fornavn like '%$search%') or (efternavn like '%$search%') or (c +pr LIKE '%$search%')",\ %attr);

Edit kudra, 2001-10-22 Added code tags

Replies are listed 'Best First'.
Re: sql select with array
by davorg (Chancellor) on Oct 22, 2001 at 13:32 UTC

    When you interpolate an array in a double quoted string, the elements of the array are separated by the contents of the $" variable. The default value for this variable is a space, so your SQL statement becomes "select fornavn efternavn cpr adresse zip city telefon mobil g_afsluttet bemyndigelse_til tjenestested id pic from people..." which is invalid SQL.

    To fix the problem, you can set $" to a comma, but whenever you change the value of a Perl special variable, you should localise the change like this:

    { local $" = ','; my $row = $dbh->selectall_arrayref("select @selector from people whe +re (fornavn like '%$search%') or (efternavn like '%$search%') or (cpr + LIKE '%$search%')",\ %attr); }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you don't talk about Perl club."

Re: sql select with array
by blakem (Monsignor) on Oct 22, 2001 at 13:31 UTC
    When @selector is interpolated into your string, the elements are being separated by a space. Since SQL engines expect those fields to be separated by commas, your code is bombing out. So, you need to add commas into your SQL to get it to work properly.

    One "questionable" (but fun) way of doing this is by modifying the global $" variable, which is the separator used when interpolating arrays into strings. Its default value is a single space, which explains the above situation.
    Setting it to ',' yields code like this: (warning, untested)

    my $sql; { local $" = ','; # localize $" for use in the next statement $sql = "select @selector from people where foo like '%bar%'" } my $row = $dbh->selectall_arrayref($sql) or die "SQL Error: $sql";

    -Blake

      I'm interested to know why you think that changing $" is a "questionable" solution. It seems to me that it's situations like this that $" was invented for.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you don't talk about Perl club."

        I would say it "questionable" as well. (And I use it all the time. :-) Three reasons.
        1. I try to avoid global variables as much as possible.
        2. $" is line noise and accordingly easy to miss by a maintainer (who is most likely not at my level of perl).
        3. Beginners are much more likely to set global variables than to localize them.
        (4. $" screws up the syntax highlighting in many editors.)

        Join() performs the same task in a much more maintainable way, so its not really needed. Also, if you think about it join is about the same or less in terms of usage.

        local $"=','; my $s="@list"; my $s=join(',',@list);

        As i said though I use it in obfus, snippets and temporary debuging code all the time. But only cause I like to. :-)

        Yves
        --
        You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)

        I always hesitate to tell anonymonks to go tinkering with global vars..... Its the case of "a little information can be dangerous." Once you understand the full implications, I think it is a fine solution, though.

        -Blake

Re: sql select with array
by busunsl (Vicar) on Oct 22, 2001 at 13:26 UTC
    Please enclose your code in code-tags, read the help pages about that.

    Now to your problem:

    You have to join your column names like this:

    my $row = $dbh->selectall_arrayref('select ' . join(',', @selector) . " from people where (fornavn like '%$search%') or (efternavn like '%$s +earch%') or (cpr LIKE '%$search%')",\ %attr);
      Or, if you're not stuck on using just $dbh->selectall_arrayref and your database supports placeholders, couldn' you do this?
      $sth = $dbh->prepare("SELECT " . '? ' x $#selector . "FROM people WHER +E (fornavn LIKE '%$search%') or (eternavn LIKE '%$search%') or (cpr L +IKE '%$search%'", \%attr); #dunno if you can do the \%attr part... $sth->execute(@selector);
      And then you've got a statement handle to get your data from.. I don't know if it's more efficient, but it seems a bit more readable to me.
        No, you can't. Placeholders are allowed in where clauses and as update values only.

        Well, _some_ DBD's support them in the way you'd use them, but I wouldn't rely on that.

Re: sql select with array
by jeroenes (Priest) on Oct 22, 2001 at 13:29 UTC
    In general "@array" concatenates the items in the array in to a string without any separator (but see perlvar). In the case of SQL, you'd probably like comma's between your items (see join):
    ...._arrayref( "select ". join( ', ', @selector) . " from people .... "
    Jeroen
Re: sql select with array
by Anonymous Monk on Oct 22, 2001 at 13:35 UTC
    Great, Thanks
    BR Soren

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://120473]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2024-04-25 21:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found