MySQL based functions


/ Published in: Perl
Save to your folder(s)



Copy this code and paste it in your HTML
  1. sub db_connect {
  2. my ($dbname, $dbuser, $dbpass) = @_;
  3. my $dbh = DBI->connect("DBI:mysql:$dbname",$dbuser,$dbpass);
  4. #$dbh->do(qq{set character set 'utf8';});
  5. return $dbh;
  6. }
  7.  
  8. sub do_sql {
  9. # Takes: $dbh, $sql
  10. # Returns: status
  11. my $dbh = shift || die "Database not connected!\n";
  12. my $sql = shift || die "Missing SQL statement???\n";
  13. return $dbh->do($sql);
  14. }
  15.  
  16. sub execute_sql {
  17. # Takes: $dbh, $sql
  18. # Returns: $result_arrayref
  19. my $dbh = shift || die "Database not connected!\n";
  20. my $sql = shift || die "Missing SQL statement???\n";
  21. my $sth = $dbh->prepare($sql);
  22. $sth->execute;
  23. my $result = $sth->fetchall_arrayref({}); # {} => Return arrayref of hashrefs
  24. return $result;
  25. }
  26.  
  27. sub do_insert {
  28. #takes: $dbh, $table, $datahash
  29. #returns: status
  30. my $dbh = shift || die "Database not connected!\n";
  31. my $table = shift || die "Missing table!\n";
  32. my $datahash = shift || die "Nothing to insert!\n";
  33. my $insert = "INSERT INTO $table (" . join(',', keys %$datahash) . ') VALUES (' . join(',', values %$datahash) . ');';
  34. return &do_sql($dbh, $insert);
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.