Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Looking for a simpler DBI solution.

by Anonymous Monk
on Nov 02, 2001 at 20:50 UTC ( #122841=note: print w/replies, xml ) Need Help??

in reply to Looking for a simpler DBI solution.

I am building a small web based application and have abstracted my database calls (updates, queries and deletes) into a single sub that I then call with up to 2 parameters. The first parameter is the query itself. The second is any data to be inserted. The sub will return the results (if any). This has really helped me to simplify the database calls within my application.

sub db_do { my (%attr) = ( RaiseError => '1'); my $dbh = DBI->connect('DBI:mysql:DATABASE:localhost', 'userna +me', 'password', \%attr); my ($dbq) = shift; my @args = @_; my $sth = $dbh->prepare("$dbq"); $sth->execute(@args); my $result; my @results; if ($dbq =~ /select/i) { my @row; while (@row = $sth->fetchrow_array) { push @results, [ @row ]; } $result = \@results; } $sth->finish; $dbh->disconnect; return $result; } Note that this doesn't handle errors as it should yet, but is function +al. An example of how I use it would be: my $dbq = qq{ INSERT INTO pagers (ptype,pnum,ppin,enum) VALUES (?,?,?, +?) }; my $res = db_do("$dbq", "$ptype", "$pnum", "$ppin", "$enum"); or for a simple select: my $dbq = qq{ SELECT email from email where email = ? }; my $res = db_do("$dbq", "$email");

Without seeing your data, it's difficult to say, but your problem might be that your data needs to be quoted properly to accomplish the insert. The $sth = $dbh->prepare($dbq) statment above will accomplish this for you.

Hope this helps!

Jerald Jackson

Edited 2001-11-02 by Ovid

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2021-05-11 01:07 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (111 votes). Check out past polls.