Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: OOP: How to construct multiple instances of a class at once

by runrig (Abbot)
on Nov 14, 2012 at 23:00 UTC ( #1003899=note: print w/ replies, xml ) Need Help??


in reply to OOP: How to construct multiple instances of a class at once

Here is an incomplete example:

sub new { my ($class, @ids) = @_; my @users; my $sql = "SELECT user_id, user_name FROM users WHERE user_id IN (" +. join(",", @ids) . ")"; my $sth = $dbh->prepare($sql); $sth->execute(); $sth->bind_cols(\my ($id, $name)); while ( $sth->fetch() ) { push @users, bless({ user_id => $id, user_name => $name, }, $class); }; return wantarray ? @users : $users[0]; }
The @ids should be scrubbed for Bobby Tables issues, but that is also the case in your original code.


Comment on Re: OOP: How to construct multiple instances of a class at once
Download Code
Re^2: OOP: How to construct multiple instances of a class at once
by Tanktalus (Canon) on Nov 15, 2012 at 03:03 UTC

    Scrubbing for Bobby Tables issues? No, the SQL needs to be written for those issues.

    my $sql = 'SELECT user_id, user_name FROM users WHERE user_id IN (' . +join(',', ('?') x @ids) . ')'; #... $sth->execute(@ids);
    Especially since perl makes this so trivially easy, as compared to, say, C.

      If the ids were strings, I might use map $dbh->quote($_), @ids, but since they're probably integers, validating that they're /^\d+$/ is probably good enough. Either is also easy.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003899]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2014-12-26 09:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls