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


In reply to Re: Looking for a simpler DBI solution. by Anonymous Monk
in thread Looking for a simpler DBI solution. by Zecho

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.