Cover V08, I07
Article
Figure 1
Listing 1
Listing 2
Listing 3
Sidebar 1

jul99.tar


Listing 2: Insert information into the database

     sub create_person {
       local(*person) = @_;
       my $id         = 0;

     ;# Find the next ID number; if it doesn't exist, set it to 1.
       my $sth = $dbh->prepare(q{
         SELECT MAX(id) FROM Person
       });
       $rv = $sth->execute;
       if ($rv > 0) {
         ($id) = $sth->fetchrow_array;  ;# ($id) is a single-element array
       }
       $id++;

     ;# Make sure everything is properly quoted for the database
       my $firstname = $dbh->quote($person{firstname});
       my $lastname  = $dbh->quote($person{lastname});
       my $dept      = $dbh->quote($person{dept});
       my $phone     = $dbh->quote($person{phone});

       $sth = $dbh->prepare(qq{
         INSERT INTO   Person (
                               id,
                               first_name,
                               last_name,
                               dept,
                               phone)
                       VALUES (
                               $id,
                               $firstname,
                               $lastname,
                               $dept,
                               $phone)
                     });
       $rv = $sth->execute;
     }  ;# End sub create_person

   Call this subroutine with an associative array with the proper keys:

     %test(
          firstname => 'Tony',
          lastname  => 'Taylor',
          dept      => 'ISD',
          phone     => 'BR-549'
        );
     &create_person(*test);