feature | daily | high gear | we::blog | contact      
 
Search
Feature / 16 Oct 2000 / Using Perl DBI to interface to MySQL
Web Search
Anyone can submit a news item, but only members can comment on them! New users, sign up here.
 
  danchan Login  
  Nickname  
   
  Password  
   
  Remember  
   

New openlog - the unbearable lightness of blog - plus free weblogging with comments, easy syndication and no ads!

Get [danchan] for your PDA!

Every daily news item!

10 latest comments

  Archive  
  2001 December
2001 November
2001 October
2001 September
2001 August
2001 July
2001 June
2001 May
2001 April
2001 March
2001 February
2001 January
2000 December
2000 November
2000 October
2000 September
2000 August
2000 July
2000 June
 

Using Perl DBI to interface to MySQL

Why Perl? Why not PHP? After all, PHP4 is supposed to be fast now that it's using a new interpreter.

Because Perl is still what's most widely used. I like going with the industry standard. Perl has massive support online and the most books written about it. There is CPAN, the Comprehensive Perl Archive Network, where you'll find modules to do almost anything you'd want. DBI gives you an interface that'll work with the "primitive" CSV format (comma separated value text files) all the way up to the highest end Oracle RDBMS.

Let's start by connecting to the database:

use DBI;

my $dsn = 'DBI:mysql:my_database:localhost';
my $db_user_name = 'admin';
my $db_password = 'secret';
my ($id, $password);
my $dbh = DBI->connect($dsn, $db_user_name, $db_password);

Let's assume we've received as form input a nickname and password from a login screen. So right now,

$input_nickname = 'Cowlick' and $input_password = 'udder'

We want to verify that the entered password matches what we have in our database.

my $sth = $dbh->prepare(qq{
    select id, password from users 
        where nickname = $input_nickname
});
$sth->execute();

Notice there is no command-terminating semi-colon.

How do we get the results? Since we only expect one row,

($id, $password) = $sth->fetchrow_array();
$sth->finish(): # we're done with this query
if ($input_password eq $password) # case-sensitive
{
     ... # login successful
}

What if our result is more than one row? Successive calls to

$sth->fetchrow_array()

will return the rest of the result set.

my $sth = $dbh->prepare(qq{
    select nickname, favorite_number from users
});
$sth->execute();
while (my ($nickname, $favorite_number) = 
    $sth->fetchrow_array())  # keep fetching until 
                             # there's nothing left
{
     print "$nickname, $favorite_number\n";
}
$sth->finish();

If we want to save the entire result set first for processing later,

my (@matrix) = ();
while (my @ary = $sth->fetchrow_array())
{
    push(@matrix, [@ary]);  # [@ary] is a reference
}
$sth->finish();

A reference, for C programers, can be thought of as a pointer. The Matrix is now an array of array references, or a two-dimensional array.

You can access row $i with:

@{matrix[$i]}

Or, you can access a specific row and column ($i, $j) in the table with:

$matrix[$i][$j]

For MySQL operations that don't return a result you can use the do method instead of prepare then execute.

$dbh->do("insert into message_votes 
  (message_id, user_id, vote) values (1, 3, 'good')");

When you're done with the database:

$dbh->disconnect();

MySQL That should be enough to get you started. You can see that using Perl DBI is a matter of calling a method with the MySQL command as a string.

For more in-depth information regarding Perl DBI and MySQL refer to the book MySQL (OTHER NEW RIDERS) by Paul Dubois. Great reviews on Amazon convinced me to buy it and while I can't quite rave about the book, because it's hard to find what you want most of the time, it seems very competently written. Of course, I have no frame of reference since this is the only MySQL book I've looked at.

CGI Programming with PerlFor the best all-around CGI book out there, you must get the excellent CGI Programming with Perl (2nd Edition) published by O'Reilly. You should know some Perl before starting in on this but you'll learn more than a little bit about everything CGI by the time you've finished. Plenty of relevant examples and excellent sections on Security, DBI, and Maintaining State make this book a must have. Disregard the bad reviews on Amazon unless you're the kind of person who likes to type in the examples from the book, in which case, you will have a tough time. Use it instead to learn the concepts and then write your own code!

page 1, 2, 3, 4
 
4 comments
 
posted by bionicroach on 16 Dec 2000
  3 out of 3 members found this comment interesting.  
 

Thanks for posting the MySQL tutorial!

I have a fair amount of experience with SQL RDBMS's in general from years of battling the likes of MS SQL Server and Access in the retail point of sale system trenches, but my web programming experience is just about nil. However, Since I generally like to learn something by pretending that I know what I'm doing until I stop failing at it, I have decided to start my web programming career by messing around with Perl/MySQL as the basis for a few web-based project ideas that I have. (Read: It would be really cool if this series would happen to continue!!)

I also appreciated the section on setting up a Win 98 development environment - it should save me a lot of cash to not have to pay for web space while I'm still trying to figure everything out.

Assuming I eventually come up with something that works, I was also wondering if anyone knows of a decent hosting service that supports MySQL and isn't too expensive...

Thanks!

p.s. - If anyone wants me to babysit their Alfred Dunhill Carbon Fibre Pen, please let me know!

     
posted by brewfan9 on 08 May 2002
  0 out of 0 members found this comment interesting.  
 

DBI Tutorial

Thanks for setting this up, it makes for good reading in a world that is pretty much turning it's databases over to the under qualified php. my opinion of course. I've had good experience with a hosting company hartlandhosting.net they are cheep too :)

     
posted by Munkita on 04 May 2003
  0 out of 0 members found this comment interesting.  
 

New to MySQL & Perl and very happy with result

This is a great tutorial. As a new user, I thought that MySQL and Perl worked really well (through DBI). MySQL and Perl for the Web by Paul DuBois is a great book as well. I was really happy with how easy it was to access and change the database through Perl.

Warning about the book... the book does talk about imbedding HTML files into the cgi but does not really deal with seperate HTML files. I'm sure this is easy enough to do, but I have not yet learned the syntax for it within the Perl.

With very basic knowledge, I was pretty happy with the result. MySQL was difficult to configure because the documentation is not very good through mysql.com. I actually ended up tapping into another server that had MySQL previously installed. If you do that, make sure to grant admin rights to username@yourlocalhost instead of just the username (because it will grant rights to username@externalserver). The DuBois book goes through this as well.

Good Luck!!

     
posted by mrcullers on 30 Dec 2004
  0 out of 0 members found this comment interesting.  
 

Thank You

I have been programming since 1982. I have studied many languages. I have been using flat file databases for many many years. I am currently working with a client that insists that I switch over to mysql for security reasons. I always knew that to learn mysql commands would be simple because I do have the mind for it. However, the thing that I was afraid of the most was, when I do finally decide to research it, it would be complicated to understand because most technical writers do not understand that less is more. The concept of programming has revolved around the idea that less is more thus causing what use to be 10 lines of code is now 1 line of concept. Basically. Thank you for making an instructional sheet, like this one, that by reading only 2 times has taught me what I need to get started.

Seriously, Thank you.. After only 30 minutes of reading I am ready for my next lesson plan. Anyone wanting to get the jest of mysql access using dbi in a cgi enviroment, read this artical.

     
  DAYPOP  
Searching the Living Web
Daypop indexes news sites and weblogs every day to give you the latest relevant information.

Weblogging

Super-customizable weblogging with comments
Add comments to your web site or create a weblog of your own!

Web Caching
Accelerate your website!
Improve your website's responsiveness by preloading your site content into a user's browser cache.

Contents
1
Introduction to MySQL (using Perl DBI)
2
Simple MySQL Commands
3
MySQL types and primary key
4
Using Perl DBI to interface to MySQL
Questions? Comments? Send all mail to: dc@danchan.com