PHP之购物车

该文章记录了购物车的实现代码,仅供参考

book_sc_fns.php

<?php
  include_once('output_fns.php');
include_once('book_fns.php');
include_once('db_fns.php');
include_once("user_auth_fns.php");
include_once("admin_fns.php");
include_once("data_valid_fns.php");
include_once("order_fns.php");
?>

output_fns.php

<?php

function do_html_header($title = '') {
  // print an HTML header

  // declare the session variables we want access to inside the function
  if (!$_SESSION['items']) {
    $_SESSION['items'] = '0';
  }
  if (!$_SESSION['total_price']) {
    $_SESSION['total_price'] = '0.00';
  }
?>
  <html>
  <head>
    <title><?php echo $title; ?></title>
    <style>
      h2 { font-family: Arial, Helvetica, sans-serif; font-size: 22px; color: red; margin: 6px }
      body { font-family: Arial, Helvetica, sans-serif; font-size: 13px }
      li, td { font-family: Arial, Helvetica, sans-serif; font-size: 13px }
      hr { color: #FF0000; width=70%; text-align=center}
      a { color: #000000 }
    </style>
  </head>
  <body>
  <table width="100%" border="0" cellspacing="0" bgcolor="#cccccc">
  <tr>
  <td rowspan="2">
  <a href="index.php"><img src="images/Book-O-Rama.gif" alt="Bookorama" border="0"
       align="left" valign="bottom" height="55" width="325"/></a>
  </td>
  <td align="right" valign="bottom">
  <?php
     if(isset($_SESSION['admin_user'])) {
       echo "&nbsp;";
     } else {
       echo "Total Items = ".$_SESSION['items'];
     }
  ?>
  </td>
  <td align="right" rowspan="2" width="135">
  <?php
     if(isset($_SESSION['admin_user'])) {
       display_button('logout.php', 'log-out', 'Log Out');
     } else {
       display_button('show_cart.php', 'view-cart', 'View Your Shopping Cart');
     }
  ?>
  </tr>
  <tr>
  <td align="right" valign="top">
  <?php
     if(isset($_SESSION['admin_user'])) {
       echo "&nbsp;";
     } else {
       echo "Total Price = $".number_format($_SESSION['total_price'],2);
     }
  ?>
  </td>
  </tr>
  </table>
<?php
  if($title) {
    do_html_heading($title);
  }
}

function do_html_footer() {
  // print an HTML footer
?>
  </body>
  </html>
<?php
}

function do_html_heading($heading) {
  // print heading
?>
  <h2><?php echo $heading; ?></h2>
<?php
}

function do_html_URL($url, $name) {
  // output URL as link and br
?>
  <a href="<?php echo $url; ?>"><?php echo $name; ?></a><br />
<?php
}

function display_categories($cat_array) {
  if (!is_array($cat_array)) {
     echo "<p>No categories currently available</p>";
     return;
  }
  echo "<ul>";
  foreach ($cat_array as $row)  {
    $url = "show_cat.php?catid=".$row['catid'];
    $title = $row['catname'];
    echo "<li>";
    do_html_url($url, $title);
    echo "</li>";
  }
  echo "</ul>";
  echo "<hr />";
}

function display_books($book_array) {
  //display all books in the array passed in
  if (!is_array($book_array)) {
    echo "<p>No books currently available in this category</p>";
  } else {
    //create table
    echo "<table width=\"100%\" border=\"0\">";

    //create a table row for each book
    foreach ($book_array as $row) {
      $url = "show_book.php?isbn=".$row['isbn'];
      echo "<tr><td>";
      if (@file_exists("images/".$row['isbn'].".jpg")) {
        $title = "<img src=\"images/".$row['isbn'].".jpg\"
                  style=\"border: 1px solid black\"/>";
        do_html_url($url, $title);
      } else {
        echo "&nbsp;";
      }
      echo "</td><td>";
      $title = $row['title']." by ".$row['author'];
      do_html_url($url, $title);
      echo "</td></tr>";
    }

    echo "</table>";
  }

  echo "<hr />";
}

function display_book_details($book) {
  // display all details about this book
  if (is_array($book)) {
    echo "<table><tr>";
    //display the picture if there is one
    if (@file_exists("images/".$book['isbn'].".jpg"))  {
      $size = GetImageSize("images/".$book['isbn'].".jpg");
      if(($size[0] > 0) && ($size[1] > 0)) {
        echo "<td><img src=\"images/".$book['isbn'].".jpg\"
              style=\"border: 1px solid black\"/></td>";
      }
    }
    echo "<td><ul>";
    echo "<li><strong>Author:</strong> ";
    echo $book['author'];
    echo "</li><li><strong>ISBN:</strong> ";
    echo $book['isbn'];
    echo "</li><li><strong>Our Price:</strong> ";
    echo number_format($book['price'], 2);
    echo "</li><li><strong>Description:</strong> ";
    echo $book['description'];
    echo "</li></ul></td></tr></table>";
  } else {
    echo "<p>The details of this book cannot be displayed at this time.</p>";
  }
  echo "<hr />";
}

function display_checkout_form() {
  //display the form that asks for name and address
?>
  <br />
  <table border="0" width="100%" cellspacing="0">
  <form action="purchase.php" method="post">
  <tr><th colspan="2" bgcolor="#cccccc">Your Details</th></tr>
  <tr>
    <td>Name</td>
    <td><input type="text" name="name" value="" maxlength="40" size="40"/></td>
  </tr>
  <tr>
    <td>Address</td>
    <td><input type="text" name="address" value="" maxlength="40" size="40"/></td>
  </tr>
  <tr>
    <td>City/Suburb</td>
    <td><input type="text" name="city" value="" maxlength="20" size="40"/></td>
  </tr>
  <tr>
    <td>State/Province</td>
    <td><input type="text" name="state" value="" maxlength="20" size="40"/></td>
  </tr>
  <tr>
    <td>Postal Code or Zip Code</td>
    <td><input type="text" name="zip" value="" maxlength="10" size="40"/></td>
  </tr>
  <tr>
    <td>Country</td>
    <td><input type="text" name="country" value="" maxlength="20" size="40"/></td>
  </tr>
  <tr><th colspan="2" bgcolor="#cccccc">Shipping Address (leave blank if as above)</th></tr>
  <tr>
    <td>Name</td>
    <td><input type="text" name="ship_name" value="" maxlength="40" size="40"/></td>
  </tr>
  <tr>
    <td>Address</td>
    <td><input type="text" name="ship_address" value="" maxlength="40" size="40"/></td>
  </tr>
  <tr>
    <td>City/Suburb</td>
    <td><input type="text" name="ship_city" value="" maxlength="20" size="40"/></td>
  </tr>
  <tr>
    <td>State/Province</td>
    <td><input type="text" name="ship_state" value="" maxlength="20" size="40"/></td>
  </tr>
  <tr>
    <td>Postal Code or Zip Code</td>
    <td><input type="text" name="ship_zip" value="" maxlength="10" size="40"/></td>
  </tr>
  <tr>
    <td>Country</td>
    <td><input type="text" name="ship_country" value="" maxlength="20" size="40"/></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><p><strong>Please press Purchase to confirm
         your purchase, or Continue Shopping to add or remove items.</strong></p>
     <?php display_form_button("purchase", "Purchase These Items"); ?>
    </td>
  </tr>
  </form>
  </table><hr />
<?php
}

function display_shipping($shipping) {
  // display table row with shipping cost and total price including shipping
?>
  <table border="0" width="100%" cellspacing="0">
  <tr><td align="left">Shipping</td>
      <td align="right"> <?php echo number_format($shipping, 2); ?></td></tr>
  <tr><th bgcolor="#cccccc" align="left">TOTAL INCLUDING SHIPPING</th>
      <th bgcolor="#cccccc" align="right">$ <?php echo number_format($shipping+$_SESSION['total_price'], 2); ?></th>
  </tr>
  </table><br />
<?php
}

function display_card_form($name) {
  //display form asking for credit card details
?>
  <table border="0" width="100%" cellspacing="0">
  <form action="process.php" method="post">
  <tr><th colspan="2" bgcolor="#cccccc">Credit Card Details</th></tr>
  <tr>
    <td>Type</td>
    <td><select name="card_type">
        <option value="VISA">VISA</option>
        <option value="MasterCard">MasterCard</option>
        <option value="American Express">American Express</option>
        </select>
    </td>
  </tr>
  <tr>
    <td>Number</td>
    <td><input type="text" name="card_number" value="" maxlength="16" size="40"></td>
  </tr>
  <tr>
    <td>AMEX code (if required)</td>
    <td><input type="text" name="amex_code" value="" maxlength="4" size="4"></td>
  </tr>
  <tr>
    <td>Expiry Date</td>
    <td>Month
       <select name="card_month">
       <option value="01">01</option>
       <option value="02">02</option>
       <option value="03">03</option>
       <option value="04">04</option>
       <option value="05">05</option>
       <option value="06">06</option>
       <option value="07">07</option>
       <option value="08">08</option>
       <option value="09">09</option>
       <option value="10">10</option>
       <option value="11">11</option>
       <option value="12">12</option>
       </select>
       Year
       <select name="card_year">
       <?
       for ($y = date("Y"); $y < date("Y") + 10; $y++) {
         echo "<option value=\"".$y."\">".$y."</option>";
       }
       ?>
       </select>
  </tr>
  <tr>
    <td>Name on Card</td>
    <td><input type="text" name="card_name" value = "<?php echo $name; ?>" maxlength="40" size="40"></td>
  </tr>
  <tr>
    <td colspan="2" align="center">
      <p><strong>Please press Purchase to confirm your purchase, or Continue Shopping to
      add or remove items</strong></p>
     <?php display_form_button('purchase', 'Purchase These Items'); ?>
    </td>
  </tr>
  </table>
<?php
}

function display_cart($cart, $change = true, $images = 1) {
  // display items in shopping cart
  // optionally allow changes (true or false)
  // optionally include images (1 - yes, 0 - no)

   echo "<table border=\"0\" width=\"100%\" cellspacing=\"0\">
         <form action=\"show_cart.php\" method=\"post\">
         <tr><th colspan=\"".(1 + $images)."\" bgcolor=\"#cccccc\">Item</th>
         <th bgcolor=\"#cccccc\">Price</th>
         <th bgcolor=\"#cccccc\">Quantity</th>
         <th bgcolor=\"#cccccc\">Total</th>
         </tr>";

  //display each item as a table row
  foreach ($cart as $isbn => $qty)  {
    $book = get_book_details($isbn);
    echo "<tr>";
    if($images == true) {
      echo "<td align=\"left\">";
      if (file_exists("images/".$isbn.".jpg")) {
         $size = GetImageSize("images/".$isbn.".jpg");
         if(($size[0] > 0) && ($size[1] > 0)) {
           echo "<img src=\"images/".$isbn.".jpg\"
                  style=\"border: 1px solid black\"
                  width=\"".($size[0]/3)."\"
                  height=\"".($size[1]/3)."\"/>";
         }
      } else {
         echo "&nbsp;";
      }
      echo "</td>";
    }
    echo "<td align=\"left\">
          <a href=\"show_book.php?isbn=".$isbn."\">".$book['title']."</a>
          by ".$book['author']."</td>
          <td align=\"center\">\$".number_format($book['price'], 2)."</td>
          <td align=\"center\">";

    // if we allow changes, quantities are in text boxes
    if ($change == true) {
      echo "<input type=\"text\" name=\"".$isbn."\" value=\"".$qty."\" size=\"3\">";
    } else {
      echo $qty;
    }
    echo "</td><td align=\"center\">\$".number_format($book['price']*$qty,2)."</td></tr>\n";
  }
  // display total row
  echo "<tr>
        <th colspan=\"".(2+$images)."\" bgcolor=\"#cccccc\">&nbsp;</td>
        <th align=\"center\" bgcolor=\"#cccccc\">".$_SESSION['items']."</th>
        <th align=\"center\" bgcolor=\"#cccccc\">
            \$".number_format($_SESSION['total_price'], 2)."
        </th>
        </tr>";

  // display save change button
  if($change == true) {
    echo "<tr>
          <td colspan=\"".(2+$images)."\">&nbsp;</td>
          <td align=\"center\">
             <input type=\"hidden\" name=\"save\" value=\"true\"/>
             <input type=\"image\" src=\"images/save-changes.gif\"
                    border=\"0\" alt=\"Save Changes\"/>
          </td>
          <td>&nbsp;</td>
          </tr>";
  }
  echo "</form></table>";
}

function display_login_form() {
  // dispaly form asking for name and password
?>
 <form method="post" action="admin.php">
 <table bgcolor="#cccccc">
   <tr>
     <td>Username:</td>
     <td><input type="text" name="username"/></td></tr>
   <tr>
     <td>Password:</td>
     <td><input type="password" name="passwd"/></td></tr>
   <tr>
     <td colspan="2" align="center">
     <input type="submit" value="Log in"/></td></tr>
   <tr>
 </table></form>
<?php
}

function display_admin_menu() {
?>
<br />
<a href="index.php">Go to main site</a><br />
<a href="insert_category_form.php">Add a new category</a><br />
<a href="insert_book_form.php">Add a new book</a><br />
<a href="change_password_form.php">Change admin password</a><br />
<?php
}

function display_button($target, $image, $alt) {
  echo "<div align=\"center\"><a href=\"".$target."\">
          <img src=\"images/".$image.".gif\"
           alt=\"".$alt."\" border=\"0\" height=\"50\"
           width=\"135\"/></a></div>";
}

function display_form_button($image, $alt) {
  echo "<div align=\"center\"><input type=\"image\"
           src=\"images/".$image.".gif\"
           alt=\"".$alt."\" border=\"0\" height=\"50\"
           width=\"135\"/></div>";
}

?>

book_fns.php

<?php
function get_categories() {
  $conn = db_connect();
  $query = "select catid, catname from categories";
  $result = @$conn -> query($query);
  if (!$result) {
    return false;
  }

  $num_cats = @$result -> num_rows;
  if ($num_cats == 0) {
    return false;
  }

  $result = db_result_to_array($result);
  return $result;
}

function get_category_name($catid) {
  $conn = db_connect();
  $query = "select catname from categories where catid = ".$catid."";
  $result = @$conn -> query($query);
  if (!$result) {
    return false;
  }

  $num_cats = @$result -> num_rows;
  if ($num_cats == 0) {
    return false;
  }

  $row = $result -> fetch_object();
  return $row -> catname;
}

function get_books($catid) {
  $conn = db_connect();
  $query = "select * from books where catid = ".$catid."";
  $result = @$conn -> query($query);
  if (!$result) {
    return false;
  }

  $num_cats = @$result -> num_rows;
  if ($num_cats == 0) {
    return false;
  }

  $result = db_result_to_array($result);
  return $result;
}

function get_book_details($isbn) {
  if ((!$isbn) || $isbn == '') {
    return false;
  }
  $conn = db_connect();
  $query = "select * from books where isbn = ".$isbn."";
  $result = @$conn -> query($query);
  if (!$result) {
    return false;
  }

  $row = @$result -> fetch_assoc();
  return $row;
}

function calculate_price($cart) {
  $price = 0;
  if (is_array($cart)) {
    $conn = db_connect();
    foreach ($cart as $isbn => $qty) {
      $query = "select price from books where isbn='".$isbn."'";
      $result = $conn -> query($query);
      if ($result) {
        $items = $result -> fetch_object();
        $item_price = $items -> price;
        $price += $item_price * $qty;
      }
    }
  }

  return $price;
}

function calculate_items($cart) {
  $items = 0;
  if (is_array($cart)) {
    $conn = db_connect();
    foreach ($cart as $isbn => $qty) {
      $items += $qty;
      }
  }

  return $items;
}

function calculate_shipping_cost() {
  return 20.00;
}
?>

db_fns.php

<?php

function db_connect() {
   $result = new mysqli('127.0.0.1', 'book_sc', 'password', 'book_sc');
   if (!$result) {
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}

function db_result_to_array($result) {
   $res_array = array();

   for ($count=0; $row = $result->fetch_assoc(); $count++) {
     $res_array[$count] = $row;
   }

   return $res_array;
}

?>

user_auth_fns.php

<?php

require_once('db_fns.php');

function login($username, $password) {
// check username and password with db
// if yes, return true
// else return false

  // connect to db
  $conn = db_connect();
  if (!$conn) {
    return 0;
  }

  // check if username is unique
  $result = $conn->query("select * from admin
                         where username='".$username."'
                         and password = sha1('".$password."')");
  

  if (!$result) {
     return 0;
  }

  if ($result->num_rows>0) {
     return 1;
  } else {
     return 0;
  }
}

function check_admin_user() {
// see if somebody is logged in and notify them if not

  if (isset($_SESSION['admin_user'])) {
    return true;
  } else {
    return false;
  }
}

function change_password($username, $old_password, $new_password) {
// change password for username/old_password to new_password
// return true or false

  // if the old password is right
  // change their password to new_password and return true
  // else return false
  if (login($username, $old_password)) {

    if (!($conn = db_connect())) {
      return false;
    }

    $result = $conn->query("update admin
                            set password = sha1('".$new_password."')
                            where username = '".$username."'");
    if (!$result) {
      return false;  // not changed
    } else {
      return true;  // changed successfully
    }
  } else {
    return false; // old password was wrong
  }
}


?>

admin_fns.php

<?php
// This file contains functions used by the admin interface
// for the Book-O-Rama shopping cart.

function display_category_form($category = '') {
// This displays the category form.
// This form can be used for inserting or editing categories.
// To insert, don't pass any parameters.  This will set $edit
// to false, and the form will go to insert_category.php.
// To update, pass an array containing a category.  The
// form will contain the old data and point to update_category.php.
// It will also add a "Delete category" button.

  // if passed an existing category, proceed in "edit mode"
  $edit = is_array($category);

  // most of the form is in plain HTML with some
  // optional PHP bits throughout
?>
  <form method="post"
      action="<?php echo $edit ? 'edit_category.php' : 'insert_category.php'; ?>">
  <table border="0">
  <tr>
    <td>Category Name:</td>
    <td><input type="text" name="catname" size="40" maxlength="40"
          value="<?php echo $edit ? $category['catname'] : ''; ?>" /></td>
   </tr>
  <tr>
    <td <?php if (!$edit) { echo "colspan=2";} ?> align="center">
      <?php
         if ($edit) {
            echo "<input type=\"hidden\" name=\"catid\" value=\"".$category['catid']."\" />";
         }
      ?>
      <input type="submit"
       value="<?php echo $edit ? 'Update' : 'Add'; ?> Category" /></form>
     </td>
     <?php
        if ($edit) {
          //allow deletion of existing categories
          echo "<td>
                <form method=\"post\" action=\"delete_category.php\">
                <input type=\"hidden\" name=\"catid\" value=\"".$category['catid']."\" />
                <input type=\"submit\" value=\"Delete category\" />
                </form></td>";
       }
     ?>
  </tr>
  </table>
<?php
}

function display_book_form($book = '') {
// This displays the book form.
// It is very similar to the category form.
// This form can be used for inserting or editing books.
// To insert, don't pass any parameters.  This will set $edit
// to false, and the form will go to insert_book.php.
// To update, pass an array containing a book.  The
// form will be displayed with the old data and point to update_book.php.
// It will also add a "Delete book" button.


  // if passed an existing book, proceed in "edit mode"
  $edit = is_array($book);

  // most of the form is in plain HTML with some
  // optional PHP bits throughout
?>
  <form method="post"
        action="<?php echo $edit ? 'edit_book.php' : 'insert_book.php';?>">
  <table border="0">
  <tr>
    <td>ISBN:</td>
    <td><input type="text" name="isbn"
         value="<?php echo $edit ? $book['isbn'] : ''; ?>" /></td>
  </tr>
  <tr>
    <td>Book Title:</td>
    <td><input type="text" name="title"
         value="<?php echo $edit ? $book['title'] : ''; ?>" /></td>
  </tr>
  <tr>
    <td>Book Author:</td>
    <td><input type="text" name="author"
         value="<?php echo $edit ? $book['author'] : ''; ?>" /></td>
   </tr>
   <tr>
      <td>Category:</td>
      <td><select name="catid">
      <?php
          // list of possible categories comes from database
          $cat_array=get_categories();
          foreach ($cat_array as $thiscat) {
               echo "<option value=\"".$thiscat['catid']."\"";
               // if existing book, put in current catgory
               if (($edit) && ($thiscat['catid'] == $book['catid'])) {
                   echo " selected";
               }
               echo ">".$thiscat['catname']."</option>";
          }
          ?>
          </select>
        </td>
   </tr>
   <tr>
    <td>Price:</td>
    <td><input type="text" name="price"
               value="<?php echo $edit ? $book['price'] : ''; ?>" /></td>
   </tr>
   <tr>
     <td>Description:</td>
     <td><textarea rows="3" cols="50"
          name="description"><?php echo $edit ? $book['description'] : ''; ?></textarea></td>
    </tr>
    <tr>
      <td <?php if (!$edit) { echo "colspan=2"; }?> align="center">
         <?php
            if ($edit)
             // we need the old isbn to find book in database
             // if the isbn is being updated
             echo "<input type=\"hidden\" name=\"oldisbn\"
                    value=\"".$book['isbn']."\" />";
         ?>
        <input type="submit"
               value="<?php echo $edit ? 'Update' : 'Add'; ?> Book" />
        </form></td>
        <?php
           if ($edit) {
             echo "<td>
                   <form method=\"post\" action=\"delete_book.php\">
                   <input type=\"hidden\" name=\"isbn\"
                    value=\"".$book['isbn']."\" />
                   <input type=\"submit\" value=\"Delete book\"/>
                   </form></td>";
            }
          ?>
         </td>
      </tr>
  </table>
  </form>
<?php
}

function display_password_form() {
// displays html change password form
?>
   <br />
   <form action="change_password.php" method="post">
   <table width="250" cellpadding="2" cellspacing="0" bgcolor="#cccccc">
   <tr><td>Old password:</td>
       <td><input type="password" name="old_passwd" size="16" maxlength="16" /></td>
   </tr>
   <tr><td>New password:</td>
       <td><input type="password" name="new_passwd" size="16" maxlength="16" /></td>
   </tr>
   <tr><td>Repeat new password:</td>
       <td><input type="password" name="new_passwd2" size="16" maxlength="16" /></td>
   </tr>
   <tr><td colspan=2 align="center"><input type="submit" value="Change password">
   </td></tr>
   </table>
   <br />
<?php
}

function insert_category($catname) {
// inserts a new category into the database

   $conn = db_connect();

   // check category does not already exist
   $query = "select *
             from categories
             where catname='".$catname."'";
   $result = $conn->query($query);
   if ((!$result) || ($result->num_rows!=0)) {
     return false;
   }

   // insert new category
   $query = "insert into categories values
            (0, '".$catname."')";
     
   $result = $conn->query($query);
   if (!$result) {
     return false;
   } else {
     return true;
   }
}

function insert_book($isbn, $title, $author, $catid, $price, $description) {
// insert a new book into the database

   $conn = db_connect();

   // check book does not already exist
   $query = "select *
             from books
             where isbn='".$isbn."'";

   $result = $conn->query($query);
   if ((!$result) || ($result->num_rows!=0)) {
     return false;
   }

   // insert new book
   $query = "insert into books values
            ('".$isbn."', '".$author."', '".$title."',
             '".$catid."', '".$price."', '".$description."')";

   $result = $conn->query($query);
   if (!$result) {
     return false;
   } else {
     return true;
   }
}

function update_category($catid, $catname) {
// change the name of category with catid in the database

   $conn = db_connect();

   $query = "update categories
             set catname='".$catname."'
             where catid='".$catid."'";
   $result = @$conn->query($query);
   if (!$result) {
     return false;
   } else {
     return true;
   }
}

function update_book($oldisbn, $isbn, $title, $author, $catid,
                     $price, $description) {
// change details of book stored under $oldisbn in
// the database to new details in arguments

   $conn = db_connect();

   $query = "update books
             set isbn= '".$isbn."',
             title = '".$title."',
             author = '".$author."',
             catid = '".$catid."',
             price = '".$price."',
             description = '".$description."'
             where isbn = '".$oldisbn."'";

   $result = @$conn->query($query);
   if (!$result) {
     return false;
   } else {
     return true;
   }
}

function delete_category($catid) {
// Remove the category identified by catid from the db
// If there are books in the category, it will not
// be removed and the function will return false.

   $conn = db_connect();

   // check if there are any books in category
   // to avoid deletion anomalies
   $query = "select *
             from books
             where catid=".$catid."";

   $result = @$conn->query($query);
   if ((!$result) || (@$result->num_rows > 0)) {
     return false;
   }

   $query = "delete from categories
             where catid='".$catid."'";
   $result = @$conn->query($query);
   if (!$result) {
     return false;
   } else {
     return true;
   }
}


function delete_book($isbn) {
// Deletes the book identified by $isbn from the database.

   $conn = db_connect();

   $query = "delete from books
             where isbn='".$isbn."'";
   $result = @$conn->query($query);
   if (!$result) {
     return false;
   } else {
     return true;
   }
}

?>

data_valid_fns.php

<?php

function filled_out($form_vars) {
  // test that each variable has a value
  foreach ($form_vars as $key => $value) {
     if ((!isset($key)) || ($value == '')) {
        return false;
     }
  }
  return true;
}

function valid_email($address) {
  // check an email address is possibly valid
  if (ereg("^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$", $address)) {
    return true;
  } else {
    return false;
  }
}

?>

order_fns.php

<?php
function process_card($card_details) {
  // connect to payment gateway or
  // use gpg to encrypt and mail or
  // store in DB if you really want to

  return true;
}

function insert_order($order_details) {
  // extract order_details out as variables
  extract($order_details);

  // set shipping address same as address
  if((!$ship_name) && (!$ship_address) && (!$ship_city) && (!$ship_state) && (!$ship_zip) && (!$ship_country)) {
    $ship_name = $name;
    $ship_address = $address;
    $ship_city = $city;
    $ship_state = $state;
    $ship_zip = $zip;
    $ship_country = $country;
  }

  $conn = db_connect();

  // we want to insert the order as a transaction
  // start one by turning off autocommit
  $conn->autocommit(FALSE);

  // insert customer address
  $query = "select customerid from customers where
            name = '".$name."' and address = '".$address."'
            and city = '".$city."' and state = '".$state."'
            and zip = '".$zip."' and country = '".$country."'";

  $result = $conn->query($query);

  if($result->num_rows>0) {
    $customer = $result->fetch_object();
    $customerid = $customer->customerid;
  } else {
    $query = "insert into customers values
            (0, '".$name."','".$address."','".$city."','".$state."','".$zip."','".$country."')";
    $result = $conn->query($query);

    if (!$result) {
       return false;
    }
  }

  $customerid = $conn->insert_id;

  $date = date("Y-m-d");

  $query = "insert into orders values
            (0, '".$customerid."', '".$_SESSION['total_price']."', '".$date."', '".'PARTIAL'."',
             '".$ship_name."', '".$ship_address."', '".$ship_city."', '".$ship_state."',
             '".$ship_zip."', '".$ship_country."')";

  $result = $conn->query($query);
  if (!$result) {
    return false;
  }

  $query = "select orderid from orders where
               customerid = '".$customerid."' and
               amount > (".$_SESSION['total_price']."-.001) and
               amount < (".$_SESSION['total_price']."+.001) and
               date = '".$date."' and
               order_status = 'PARTIAL' and
               ship_name = '".$ship_name."' and
               ship_address = '".$ship_address."' and
               ship_city = '".$ship_city."' and
               ship_state = '".$ship_state."' and
               ship_zip = '".$ship_zip."' and
               ship_country = '".$ship_country."'";

  $result = $conn->query($query);

  if($result->num_rows>0) {
    $order = $result->fetch_object();
    $orderid = $order->orderid;
  } else {
    return false;
  }

  // insert each book
  foreach($_SESSION['cart'] as $isbn => $quantity) {
    $detail = get_book_details($isbn);
    $query = "delete from order_items where
              orderid = '".$orderid."' and isbn = '".$isbn."'";
    $result = $conn->query($query);
    $query = "insert into order_items values
              ('".$orderid."', '".$isbn."', ".$detail['price'].", $quantity)";
    $result = $conn->query($query);
    if(!$result) {
      return false;
    }
  }

  // end transaction
  $conn->commit();
  $conn->autocommit(TRUE);

  return $orderid;
}

?>

index.php

<?php
require_once("book_sc_fns.php");

// The shopping cart needs sessions, so start one 
session_start();
// Display header 
do_html_header("Book-store");
// Show cat title
echo "<p>Please chose a category: </p>";

$cat_array = get_categories();
display_categories($cat_array);

// If login as admin, show add, delete, edit cat link
if (isset($_SESSION['admin_user'])) {
    display_button("admin.php", "admin-menu", "Admin Menu");
}
do_html_footer(); 
?>

login.php

<?php
require_once("book_sc_fns.php");
do_html_header("Administration");
display_login_form();
do_html_footer();
?>

logout.php

<?php

// include function files for this application
require_once('book_sc_fns.php');
session_start();
$old_user = $_SESSION['admin_user'];  // store  to test if they *were* logged in
unset($_SESSION['admin_user']);
session_destroy();

// start output html
do_html_header("Logging Out");

if (!empty($old_user)) {
  echo "<p>Logged out.</p>";
  do_html_url("login.php", "Login");
} else {
  // if they weren't logged in but came to this page somehow
  echo "<p>You were not logged in, and so have not been logged out.</p>";
  do_html_url("login.php", "Login");
}

do_html_footer();

?>

admin.php

<?php
require_once("book_sc_fns.php");
session_start();
if ($_POST["username"] && $_POST["passwd"]) {
    $username = $_POST["username"];
    $passwd = $_POST["passwd"];

    if (login($username, $passwd)) {
        $_SESSION["admin_user"] = $username;
    }else {
        do_html_header("Problem:");
        echo "<p>You could not be logged in.<br />
                You must be logged in to view this page.</p>";
        do_html_url("login.php", "Login");
        do_html_footer();
        exit;
    }
}

do_html_header("Administrtion");
if (check_admin_user()) {
    display_admin_menu();
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}
do_html_footer();
?>

insert_book_form.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Add a category");

if (check_admin_user()) {
    display_book_form();
    do_html_url("admin.php", "Back to administration menu");
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

insert_book.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Adding a book");

if (check_admin_user()) {
    if (filled_out($_POST)) {
        $isbn = $_POST['isbn'];
        $title = $_POST['title'];
        $author = $_POST['author'];
        $catid = $_POST['catid'];
        $price = $_POST['price'];
        $description = $_POST['description'];
        if (insert_book($isbn, $title, $author, $catid, $price, $description)) {
            echo "<p>Book <em>".stripslashes($title)."</em> was added to the database.</p>";
        }else {
            echo "<p>Book <em>".stripslashes($title)."</em> could not be added to the database.</p>";
        }
    }else {
        echo "<p>You have not filled out the form. Please try again</p>";
    }
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

insert_category_form.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Add a category");

if (check_admin_user()) {
    display_category_form();
    do_html_url("admin.php", "Back to administration menu");
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

insert_category.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Adding a category");

if (check_admin_user()) {
    if (filled_out($_POST)) {
        $catname = $_POST['catname'];
        if (insert_category($catname)) {
            echo "<p>Category \"".$catname."\" was added to the database.</p>";
        }else {
            echo "<p>Category \"".$catname."\" could not be added to the database.</p>";
        }
    }else {
        echo "<p>You have not filled out the form. Please try again</p>";
    }
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

delete_book.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Deleting book");

if (check_admin_user()) {
    if (isset($_POST['isbn'])) {
        if (delete_book($_POST['isbn'])) {
            echo "<p>Book was deleted.</p>";
        }else {
            echo "<p>Book could not be deleted.</p>";
        }
    }else {
        echo "<p>No Book specified. Please try again</p>";
    }
    do_html_url("admin.php", "Back to administation menu");
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}



do_html_footer();
?>

delete_category.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Deleting category");

if (check_admin_user()) {
    if (isset($_POST['catid'])) {
        if (delete_category($_POST['catid'])) {
            echo "<p>Category was deleted.</p>";
        }else {
            echo "<p>Category could not be deleted.</p>";
        }
    }else {
        echo "<p>No category specified. Please try again</p>";
    }
    do_html_url("admin.php", "Back to administation menu");
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

edit_book_form.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Edit book details");

if (check_admin_user()) {
    if ($book = get_book_details($_GET['isbn'])) {
        display_book_form($book);
    }else {
        echo "<p>Could not retrieve book details.</p>";
    }
    do_html_url("admin.php", "Back to administration menu");
}else { 
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

edit_book.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Updating book");

if (check_admin_user()) {
    if (filled_out($_POST)) {
        $old_isbn = $_POST['oldisbn'];
        $isbn = $_POST['isbn'];
        $title = $_POST['title'];
        $author = $_POST['author'];
        $catid = $_POST['catid'];
        $price = $_POST['price'];
        $description = $_POST['description'];
        if (update_book($old_isbn, $isbn, $title, $author, $catid, $price, $description)) {
            echo "<p>Book was updated.</p>";
        }else {
            echo "<p>Book could not be updated.</p>";
        }
    }else {
        echo "<p>You have not filled out the form. Please try again</p>";
    }
    do_html_url("admin.php", "Back to administation menu");
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

edit_category_form.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Edit category");

if (check_admin_user()) {
    if ($catname = get_category_name($_GET['catid'])) {
        $catid = $_GET['catid'];
        $cat = compact('catname', 'catid');
        display_category_form($cat);
    }else {
        echo "<p>Could not retrieve catogory details.</p>";
    }
    do_html_url("admin.php", "Back to administration menu");
}else { 
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

edit_category.php

<?php
require_once("book_sc_fns.php");
session_start();
do_html_header("Updating category");

if (check_admin_user()) {
    if (filled_out($_POST)) {
        if (update_category($_POST['catid'], $_POST['catname'])) {
            echo "<p>Category was updated.</p>";
        }else {
            echo "<p>Category could not be updated.</p>";
        }
    }else {
        echo "<p>You have not filled out the form. Please try again</p>";
    }
    do_html_url("admin.php", "Back to administation menu");
}else {
    echo "<p>You are not authorized to enter the administration area.</p>";
}

do_html_footer();
?>

change_password_form.php

<?php
require_once('book_sc_fns.php');
 session_start();
 do_html_header("Change administrator password");
 check_admin_user();

 display_password_form();

 do_html_url("admin.php", "Back to administration menu");
 do_html_footer();
?>

change_password.php

<?php
 require_once('book_sc_fns.php');
 session_start();
 do_html_header('Changing password');
 check_admin_user();
 if (!filled_out($_POST)) {
   echo "<p>You have not filled out the form completely.<br/>
         Please try again.</p>";
   do_html_url("admin.php", "Back to administration menu");
   do_html_footer();
   exit;
 } else {
   $new_passwd = $_POST['new_passwd'];
   $new_passwd2 = $_POST['new_passwd2'];
   $old_passwd = $_POST['old_passwd'];
   if ($new_passwd != $new_passwd2) {
      echo "<p>Passwords entered were not the same.  Not changed.</p>";
   } else if ((strlen($new_passwd)>16) || (strlen($new_passwd)<6)) {
      echo "<p>New password must be between 6 and 16 characters.  Try again.</p>";
   } else {
      // attempt update
      if (change_password($_SESSION['admin_user'], $old_passwd, $new_passwd)) {
         echo "<p>Password changed.</p>";
      } else {
         echo "<p>Password could not be changed.</p>";
      }
   }
 }
 do_html_url("admin.php", "Back to administration menu");
 do_html_footer();
?>

checkout.php

<?php
include("book_sc_fns.php");
session_start();
do_html_header("Checkout");

if (($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
    display_cart($_SESSION['cart'], false, 0);
    display_checkout_form();
}else {
    echo "<p>There are no items in your cart</p>";
}

display_button("show_cart.php", "continue-shopping", "Continue Shopping");

do_html_footer();
?>

process.php

<?php
include("book_sc_fns.php");
session_start();

do_html_header("Checkout");

$card_type = $_POST['card_type'];
$card_number = $_POST['card_number'];
$card_month = $_POST['card_month'];
$card_year = $_POST['card_year'];
$card_name = $_POST['card_name'];

if ($_SESSION["cart"] && ($card_type) && ($card_number) 
                    && ($card_month) && ($card_year) && ($card_name)) {
   display_cart($_SESSION['cart'], false, 0);
   display_shipping(calculate_shipping_cost());

   if (process_card($_POST)) {
       session_destroy();
       echo "<p>Thank you for shopping with us.Your order has been placed.</p>";
       display_button("index.php", "continue-shopping", "Continue Shopping");
   }else {
       echo "<p>Could not process your card.Please contact the card issuer or try again.</p>";
       display_button("purchase.php", "back", "Back");
   }
}else {
    echo "<p>You did not fill in all the fields, please try again.</p><hr />";
    display_button("purchase.php", "back", "Back");
}

do_html_footer();

?>

purchase.php

<?php
include("book_sc_fns.php");
session_start();
do_html_header("Checkout");

// Info
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$country = $_POST['country'];

// Check if filled out 
if (($_SESSION['cart']) && ($name) && ($address) && ($city) && ($zip) && ($country)) {
    if ((insert_order($_POST)) != false) {
        display_cart($_SESSION['cart'], false, 0); 
        display_shipping(calculate_shipping_cost());
         
        display_card_form($name);
        display_button('show_cart.php', 'continue-shopping', 'Continu Shopping'); 
    }else {
      echo "<p>Could not store data, please try again.</p><hr />";
      display_button('checkout.php', 'back', 'back');  
    }
}else {
    echo "<p>You did not fill in all the fields, please try again.</p><hr />";
    display_button('checkout.php', 'back', 'back');
}

do_html_footer();
?>

show_book.php

<?php

// include function files for this application
require_once('book_sc_fns.php');
session_start();

$isbn = $_GET['isbn'];
$book = get_book_details($isbn);
do_html_header($book['title']);

display_book_details($book);

$target = "index.php";
if ($book['catid']) {
    $target = "show_cat.php?catid=".$book['catid']."";
}
if (check_admin_user()) {
  display_button("edit_book_form.php?isbn=".$isbn."", "edit-item", "Edit Book");
  display_button("admin.php", "admin-menu", "Admin Menu");
  display_button($target, "continue", "Continue");
}else {
  display_button("show_cart.php?new=".$isbn."", "add-to-cart", "Add ".$book['title']." To My Shopping Cart");
  display_button($target, "continue-shopping", "Continue Shopping");
}
do_html_footer();

?>

show_cart.php

<?php
include("book_sc_fns.php");
session_start();

@$new = $_GET['new'];
if ($new) {
    // If cart is null create a new cat
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
        $_SESSION['item'] = 0;
        $_SESSION['total_price'] = '0.00';
    }

    // book count
    if (isset($_SESSION['cart'][$new])) {
        $_SESSION['cart'][$new] ++;
    }else {
        $_SESSION['cart'][$new] = 1;
    }

    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
}

// Save
if (isset($_POST['save'])) {
    foreach ($_SESSION['cart'] as $isbn => $qty) {
        if ($_POST[$isbn] == '0') {
            unset($_SESSION['cart'][$isbn]);
        }else {
            $_SESSION['cart'][$isbn] = $_POST[$isbn];
        }
    }

    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
}

do_html_header("Your shopping cart");

// Display the cart
if ($_SESSION['cart'] && (array_count_values($_SESSION['cart']))) {
    display_cart($_SESSION['cart']);
}else {
    echo "<p>There are no items in your cart</p><hr />";
}

$target = "index.php";
if ($new) {
    $detail = get_book_details($new);
    if ($detail['catid']) {
        $target = "show_cat.php?catid=".$detail['catid'];
    }
}

display_button($target, "continue-shopping", "Continue Shopping");
display_button("checkout.php", "go-to-checkout", "Go To Checkout");

do_html_footer();
?>

show_cat.php

<?php

// include function files for this application
require_once('book_sc_fns.php');
session_start();

$catid = $_GET['catid'];
$name = get_category_name($catid);

do_html_header($name);

// Get books
$book_array = get_books($catid);
display_books($book_array);

if (isset($_SESSION['admin_user'])) {
  display_button("index.php", "continue", "Continue Shopping");
  display_button("admin.php", "admin-menu", "Admin Menu");
  display_button("edit_category_form.php?catid=".$catid."", "edit-category", "Edit category");
}else {
  display_button("index.php", "continue-shopping", "Continue Shopping");
}
do_html_footer();

?>

说明

全部文件下载地址:https://pan.baidu.com/s/1pL50Ql9

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容