#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use DBI;
use strict;

print header;
print start_html("Checkout Step 1");

my $dbh = DBI->connect( "dbi:mysql:products", "webserver", "", { RaiseError => 1, AutoCommit => 1 }) or &dienice("Can't connect to database: $DBI::errstr");

# First change: detect the cookie, and bounce if it isn't found
my $cookie_id = &validate_cookie;

print <<EndHead;
<h2 align="CENTER">Order Form - Step 2</h2>
Here's what you've ordered:<br>
<form action="order2.cgi" method="POST">

# Second change:
# Reat items from the shopcart instead of form input
my $sth = $dbh->prepare("select * from shopcart, items where shopcart.cookie=? and items.stocknum=shopcart.item_number") or &dbdie;

$sth->execute($cookie_id) or &dbdie;

# Third change:
# Use fetchrow_hashref instead of fetchrow_array
# and $rec->{columnname} to refer to the column data
my $subtotal = 0;
while (my $rec = $sth->fetchrow_hashref) {
    $subtotal = $subtotal + ($rec->{price} * $rec->{qty});
    print qq(<b>$rec->{name}</b> (#$rec->{stocknum}) - $rec->{price} ea., qty: $rec->{qty}<br>\n);

if ($subtotal == 0 ) {
    &dienice("You didn't order anything!");
$subtotal = sprintf("%4.2f", $subtotal);
print <<EndForm;
Subtotal:<br> \$$subtotal
Please enter your shipping information:<br><br>

        Your Name: <input type="text" name="name" size=50>
 Shipping Address: <input type="text" name="ship_addr" size=50>
             City: <input type="text" name="ship_city" size=50>
   State/Province: <input type="text" name="ship_state" size=30>
  ZIP/Postal Code: <input type="text" name="ship_zip" size=30>
          Country: <input type="text" name="ship_country" size=30>
            Phone: <input type="text" name="phone" size=30>
            Email: <input type="text" name="email" size=30>
Payment Method:
<select name="paytype">
<option value="cc">Credit Card
<option value="check">Check/Money Order

<input type="submit" value="Place Order">

print end_html;


sub dienice {
    my ($msg) = @_;
    print "<h2>Error</h2>\n";
    print $msg;

sub validate_cookie {
    my $cookie_id = "";
    if (cookie('cart')) {
       $cookie_id = cookie('cart');
    } else {
       &dienice("You don't have a cart. (Perhaps your cart expired?)");
    my $sth = $dbh->prepare("select * from cart_cookies where cookie_id=?") or &dbdie;
    $sth->execute(cookie('cart')) or &dbdie;
    unless ($sth->fetchrow_hashref) {
       &dienice("You don't have a cart. (Perhaps your cart expired?)");
    return $cookie_id;

sub dbdie {
    my($package, $filename, $line) = caller;
    my($errmsg) = "Database error: $DBI::errstr<br>
                called from $package $filename line $line";