Listing 5: submit-cookie.pl, which takes the information from the above form, #!/usr/bin/perl -w use strict; use diagnostics; use CGI; use Mysql; # Create an instance of CGI my $query = new CGI; # Get the "user_id" cookie value, if it exists my $user_id = $query->cookie("user_id"); # Get the parameters that the user submitted my $name = $query->param("name"); my $color = $query->param("color"); # Connect to the local database server my $dbh = Mysql->connect("localhost", "test"); # If this is the user's first time visiting our site, then # create a new row in the table and create a cookie. if ($user_id == 0) { # Create our SQL command based on the form contents my $command = "insert into user_table (user_name, user_color) "; $command .= " values (\"$name\", \"$color\")"; # Execute the command my $sth = $dbh->query($command); # Get the user's unique ID in the database $user_id = $sth->insert_id; # Update the cookie with the right value my $cookie = $query->cookie(-name => "user_id", -value => $user_id); # Now that we have updated the value, produce some HTML output print $query->header(-type => "text/html", -cookie => $cookie); } # If this is a repeat visit from the user, update the appropriate # row in the table. (The cookie does not need updating.) else { # Create our SQL command to update therow my $command = "update user_table "; $command .= "set user_name = \"$name\", user_color = \"$color\" "; $command .= "where user_id = $user_id"; # Execute the command my $sth = $dbh->query($command); # Send an HTTP header print $query->header("text/html"); print "
\"$command\"
\n"; } # Now return some text to the user print $query->start_html(-title => "Thank you"); print "Thank you! You may now go to "; print 'your personalized '; print "home page.
\n"; print $query->end_html;