|
|
Think of our typical three users.
lbird |
mjordan |
tkukoc |
Initial balances are 0 (zero).
burrowww.cs.indiana.edu% mysql -ua348 -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 677 to server version: 3.23.27-beta
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
mysql> use a348
Database changed
mysql> show tables like "dgerman_BANK";
Empty set (0.01 sec)
mysql> create table dgerman_BANK (
-> username varchar(8),
-> balance float
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> insert into dgerman_BANK values (
-> 'lbird', 0), ('mjordan', 0), ('tkukoc', 0);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from dgerman_BANK;
+----------+---------+
| username | balance |
+----------+---------+
| lbird | 0 |
| mjordan | 0 |
| tkukoc | 0 |
+----------+---------+
3 rows in set (0.01 sec)
mysql> exit
Bye
burrowww.cs.indiana.edu%
Now to change the balances we simply use update.
#!/usr/bin/perl
use CGI;
$q = new CGI;
$who = $q->param('which');
$amount = $q->param('amount');
print $q->header, $q->start_html;
use DBI;
my ($dsn) = "DBI:mysql:a348"; # data source name
my ($username) = "a348"; # username
my ($password) = "a348AG"; # password
my ($dbh, $sth); # database and statement handles
my (@ary); # array for rows returned by query
# connect to the database
$dbh = DBI->connect($dsn, $username, $password, { RaiseError => 1 });
#issue query
$amount += 0;
$dbh->do ("update dgerman_BANK set balance = balance + $amount where " .
"username = '$who'") if ($who);
$sth = $dbh->prepare("select * from dgerman_BANK");
$sth->execute();
print $q->startform;
print "<table width=100%><tr> ";
# read results of query, then clean up
while (@ary = $sth->fetchrow_array()) {
# print join ("\t", @ary), "\n";
$pic = $ary[0];
$balance = $ary[1];
print qq{
<td align=center valign=middle>
<input type="radio" name="which" value="$pic"> $pic <br>
<img src=
"http://www.cs.indiana.edu/classes/a114/fall2001/lectures/nine/$pic.jpg">
<br> Balance is: ($balance) </td>
};
}
$sth->finish();
print qq{ </tr> </table><p>
Enter amount: <input type="text" name="amount" size=4> then
push <input type="submit" value="Proceed">
};
$dbh->disconnect();
print $q->endform, $q->end_html;
exit(0);
That's the equivalent of your homework 2 (part 2) calculator. Try it here. (How does this relate to the calculator, though? How is this different?)