Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

by runrig (Abbot)
on Nov 14, 2012 at 23:00 UTC ( [id://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.

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1003899]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-04-23 20:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found