Tag Archives: PHP

Use PHP Check all the field in form is not empty,here is the php page–continues with previous post

Use PHP Check all the field in form is not empty,here is the php page–continues with previous post

<?php
/*  Program name: checkBlank.php
 *  Description:  Program checks all the form fields for
 *                blank fields.
 */
 if(isset($_POST[‘sent’]) && $_POST[‘sent’] == “yes”)        #6
 {
/* check each field except middle name for blank fields */
  foreach($_POST as $field => $value)                        #9
  {
  if($value == “”)                                          #11
    {
      if($field != “middle_name”)                           #13
      {
         $blank_array[] = $field;                           #15
      } // endif field is not middle name
    } // endif field is blank
    else                                                    #18
    {
      $good_data[$field] = strip_tags(trim($value));
    }
  }  // end of foreach loop for $_POST
  /* if any fields were blank, create error message and
     redisplay form */
  if(@sizeof($blank_array) > 0)                             #25
  {
    $message = “<p style=’color: red; margin-bottom: 0;
         font-weight: bold’>
         You didn’t fill in one or more required fields.
         You must enter:
         <ul style=’color: red; margin-top: 0;
             list-style: none’ >”;
    /* display list of missing information */
    foreach($blank_array as $value)
    {
      $message .= “<li>$value</li>”;
    }
    $message .= “</ul>”;
    /* redisplay form */
    extract($good_data);                                     #40
    include(“form_phone_values.inc”);                        #41
    exit();                                                  #42
  } // endif blanks
  echo “All required fields contain information”;            #44
 } // endif submitted
 else                                                        #46
 {
  include(“form_phone_values.inc”);
 }
?>

Use PHP Check all the field in form is not empty–continues

First use class create your php form page,here is your class, you could save as form_phone_values.inc

<?php
/*  Program name: form_phone_values.inc
 *  Description:  Defines a form that collects a user’s
 *                name and phone number.
 */
$labels = array( “first_name” => “First Name”,
                 “middle_name” => “Middle Name”,
                 “last_name” => “Last Name”,
                 “phone” => “Phone”);
$submit = “Submit Phone Number”;
?>
 <html>
 <head><title>Customer Phone Number</title>
    <style type=’text/css’>
    <!–
     #form {
       margin: 1.5em 0 0 0;
       padding: 0;
     }
     #field {padding-bottom: 1em;}
     label {
     font-weight: bold;
     float: left;
     width: 20%;
     margin-right: 1em;
     text-align: right;
     }
    –>
   </style>
 </head>
 <body>
<h3>Please enter your phone number below.</h3>
<?php
 echo “<form action=’$_SERVER[PHP_SELF]’ method=’POST’>    
      <div id=’form’>”;
  if(isset($message))                                         #36
  {
     echo $message;
  }
  /* Loop that displays the form fields */
  foreach($labels as $field => $label)
  {
    echo “<div id=’field’><label for=’$field’>$label</label>
          <input id=’$field’ name=’$field’ type=’text’
             size=’50%’ maxlength=’65’
             value='”.@$$field.”‘ /></div>\n”;                #46
  }
  echo “<input type=’hidden’ name=’sent’ value=’yes’ />\n”;     #48
  echo “<input style=’margin-left: 33%’ type=’submit’
          value=’$submit’ />\n”;
?>
</form></body></html>

Use PHP displayGallery

Instead use PHP display images from your databases, Use PHP displays all the image files that are stored in a specified directory.

here is the source code:

<?php
 /* Script name: displayGallery
  * Description: Displays all the image files that are
  *              stored in a specified directory.
  */
 echo “<html><head><title>Image Gallery</title></head>
       <body>”;
 $dir = “small/”;                                #8
 $dh = opendir($dir);                                       #9
 while($filename = readdir($dh))                           #10
 {
   $filepath = $dir.$filename;                             #12
   if(is_file($filepath) and ereg(“\.jpg$”,$filename))     #13
   {
      $gallery[] = $filepath;
   }
 }
 sort($gallery);                                           #16
 foreach($gallery as $image)                               #17
 {
   echo “<hr />”;
   echo “<img src=’$image’ /><br />”;
 }
?>
</body></html>

finally, you just need create a php page read everything through your class

finally, you just need create a php page read everything through your class,here is the source code for one of the three shopping cart, for another two cart you just need to change the storeID, it make your job much easy.

<?php
session_start();
require_once(“class_OnlineStore.php”);
$storeID = “COFFEE”;
$storeInfo = array();
if(class_exists(“OnlineStore”))
{
    if(isset($_SESSION[‘currentStore’]))
    {
        $store = unserialize($_SESSION[‘currentStore’]);
    }
    else
    {
        $store = new OnlineStore();    
    }
    $store->setStoreID($storeID);
    $storeInfo =  $store->getStoreInformation();
    $store->processUserInput();
}
else
{
    $ErrorMsgs[]=”The OnlineStore class is not available!”;
    $store = null;
        
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title><?php echo $storeInfo[‘name’]; ?></title>
<link rel=”stylesheet” type=”text/css” href=”<?php echo $storeInfo[‘css_file’]; ?>” />
</head>

<body>
<h1><?php echo htmlentities($storeInfo[‘name’]); ?></h1>
<h2><?php echo htmlentities($storeInfo[‘description’]); ?></h2>
<p><?php echo htmlentities($storeInfo[‘welcome’]); ?></p>

<?php
    $store->getProductList();
    $_SESSION[‘currentStore’] = serialize($store);
?>
</body>
</html>

then you need create your class

here is the source code for your online stores class

<?php
class OnlineStore
{
    private $DBConnect = null;
    private $storeID = “”;
    private $inventory = array();
    private $shoppingCart = array();
    function __construct()
    {
        include(“inc_OnlineStoreDB.php”);
        $this->DBConnect = $DBConnect;
    }

    
    function __destruct()
    {
        if(!$this->DBConnect->connect_error)
        {
            $this->DBConnect->close();
        }
    }
    
    public function setStoreID($storeID)
    {
        if($this->storeID != $storeID)    
        {
            $this->storeID = $storeID;
            $string = “SELECT * FROM inventory WHERE storeID = ‘”.$this->storeID. “‘”;
            $result = @$this->DBConnect->query($string);
            if(!$result)
            {
                $this->storeID = “”;    
            }
            else
            {
                $this->inventory = array();
                $this->shoppingCart = array();
                while(($row = $result->fetch_assoc())!==null)    
                {
                    $this->inventory[$row[‘productID’]]=array();
                    $this->inventory[$row[‘productID’]][‘name’]=$row[‘name’];
                    $this->inventory[$row[‘productID’]][‘description’]=$row[‘description’];
                    $this->inventory[$row[‘productID’]][‘price’]=$row[‘price’];
                    $this->shoppingCart[$row[‘productID’]]=0;    
                }
            }
                
        }
        
    }
    
    public function getStoreInformation()
    {
        $retval = false;
        if($this->storeID != “”)    
        {
            $string = “SELECT * FROM store_info WHERE storeID = ‘”.$this->storeID . “‘”;
            $result = @$this->DBConnect->query($string);
            if($result)    
            {
                $retval = $result->fetch_assoc();    
            }
        }
        return($retval);
    }
    
    public function getProductList()
    {
        $retval = false;
        $subtotal = 0;
        if(count($this->inventory)>0)
        {
            echo “<table width=\”100%\”>”;
            echo “<tr><th>Product</th><th>Description</th><th>Price each</th><th># in Cart</th><th>Total Price</th><th>&nbsp;</th></tr>”;
            foreach($this->inventory as $ID => $Info)
            {
                echo “<tr><td>”    .htmlentities($Info[‘name’]).”</td>”;
                echo “<td>”.htmlentities($Info[‘description’]).”</td>”;
                printf(“<td class=\”currency\”>$%.2f</td>”,$Info[‘price’]);
                echo “<td class=’currency’>”.$this->shoppingCart[$ID].”</td>”;
                printf(“<td class=’currency’>$%.2f</td>”,$Info[‘price’]*$this->shoppingCart[$ID]);
                echo “<td><a href='”.$_SERVER[‘SCRIPT_NAME’].”?PHPSESSID=”.session_id() .”&ItemToAdd=$ID’>Add Item</a><br/>”;
                echo “<a href='”.$_SERVER[‘SCRIPT_NAME’].”?PHPSESSID=”.session_id() .”&ItemToRemove=$ID’>Remove Item</a></td>”;
                $subtotal += ($Info[‘price’] * $this->shoppingCart[$ID]);                
            }
            
            echo “<tr><td colspan=’4′>Subtotal</td>”;
            printf(“<td class=’currency’>$%.2f</td>”,$subtotal);
            echo “<td><a href='”.$_SERVER[‘SCRIPT_NAME’].”?PHPSESSID=”.session_id() .”&EmptyCart=true’>Empty Cart</a></td></tr>”;
            echo “</table>”;
            
        echo “<p align=’center’><a href=’Checkout.php?PHPSESSID=”.session_id().”&CheckOut=$storeID’>Checkout</a></p>”;    
        }
            
        return($retval);
    }
private function addItem()
{
    $ProdID = $_GET[‘ItemToAdd’];
    if (array_key_exists($ProdID,$this->shoppingCart))
    {
        $this->shoppingCart[$ProdID] += 1;    
    }
        
    
}

function __wakeup()
{
    include(“inc_OnlineStoreDB.php”);
    $this->DBConnect = $DBConnect;    
}

private function removeItem()
{
    $ProdID = $_GET[‘ItemToRemove’];
    if(array_key_exists($ProdID,$this->shoppingCart))
    {
        if($this->shoppingCart[$ProdID]>0)
            {
                $this->shoppingCart[$ProdID]-=1;                
            }
    }
    
}

private function emptyCart()
{
    foreach($this->shoppingCart as $key=>$value)
    {
        $this->shoppingCart[$key]=0;    
    }
    
}

public function processUserInput()
{
    if(!empty($_GET[‘ItemToAdd’]))
    {
        $this->addItem();    
    }
    if(!empty($_GET[‘ItemToRemove’]))
    {
        $this->removeItem();    
    }
    if(!empty($_GET[‘EmptyCart’]))
    {
        $this->emptyCart();    
    }
    
}

public function checkout()
{
        $ProductsOrdered = 0;
        foreach($this->shoppingCart as $productID =>$quantity)
        {
            if ($quantity > 0)
            {
                ++$ProductsOrdered;
                $SQLstring = “INSERT INTO orders ” .” (orderID, productID, quantity) ” .” VALUES(‘” . session_id() . “‘,” .”‘$productID’, $quantity)”;
                $QueryResult = $this->DBConnect->query($SQLstring);
            }
        }
        
        echo “<p><strong>Your order has been ” .”recorded.</strong></p>”;
}
}

?>

Create your databases first

here is your source code for your online shopping cart

— phpMyAdmin SQL Dump
— version 2.10.3
http://www.phpmyadmin.net

— Host: localhost
— Generation Time: Jun 23, 2013 at 10:26 AM
— Server version: 5.0.51
— PHP Version: 5.2.6

SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;


— Database: `online_stores`

— ——————————————————–


— Table structure for table `inventory`

CREATE TABLE `inventory` (
  `storeID` varchar(10) default NULL,
  `productID` varchar(10) NOT NULL,
  `name` varchar(100) default NULL,
  `description` varchar(200) default NULL,
  `price` float default NULL,
  PRIMARY KEY  (`productID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


— Dumping data for table `inventory`

INSERT INTO `inventory` VALUES (‘COFFEE’, ‘COFFEE001’, ‘Jamaican Blue Mountain Coffee’, ‘This extraordinary coffee, famous for its exquisite flavor and strong body, is grown in teh majestic Blue Mountain range in Jamaica. Weight: 1 pound.’, 22.95);
INSERT INTO `inventory` VALUES (‘COFFEE’, ‘COFFEE002’, ‘Blue Grove Hawaiian Maui Premium Coffee’, ‘This delightful coffee has an aroma that is captivatingly rich and nutty with a faint hint of citrus. Weight: 1 pound.’, 18.89);
INSERT INTO `inventory` VALUES (‘COFFEE’, ‘COFFEE003’, ‘Sumatra Supreme Coffee’, ‘One of the finest coffees in the world, medium roasted to accentuate its robust character. Weight: 5 pounds.’, 29.95);
INSERT INTO `inventory` VALUES (‘COFFEE’, ‘COFFEE004’, ‘Pure Kona Coffee’, ‘Grown and processed using traditional Hawaiian methods, then roasted in small batches to maintain peak freshness and flavor. Weight: 10 ounces.’, 21.45);
INSERT INTO `inventory` VALUES (‘COFFEE’, ‘COFFEE005’, ‘Guatemala Antigua Coffee’, ‘An outstanding coffee with a rich, spicy, and smokey flavor. Weight: 10 ounces.’, 7.5);
INSERT INTO `inventory` VALUES (‘ANTIQUE’, ‘ANTIQUE001’, ‘Set of four Shaker ladderback chairs’, ‘From the early 1800”s, this set of four matching ladderback chairs in the traditional Shaker style have been in the same family for eight generations. All four have the original rush seats (one slight’, 12000);
INSERT INTO `inventory` VALUES (‘ANTIQUE’, ‘ANTIQUE002’, ‘Hepplewhite Secretary’, ‘All original glass and hardware. Made of mahogany, brass and glass. All decorative inlays and finials intact. Some minor condition issues (bumps and nicks) that add to, rather than detract from, the h’, 19500);
INSERT INTO `inventory` VALUES (‘ANTIQUE’, ‘ANTIQUE003’, ‘Empire Sideboard’, ‘Mahogany primary with cypress secondaries. Three drawers above three cupboards. From an ante-bellum Louisiana estate. Excellent condition.’, 3450);
INSERT INTO `inventory` VALUES (‘ANTIQUE’, ‘ANTIQUE004’, ‘Gothic Bookcase’, ‘All walnut with blocked corners and glazed sliding doors. This unit has a dentillated pediment and a molded cornice. Wonderful condition, made in New York in the early 1800”s’, 14500);
INSERT INTO `inventory` VALUES (‘ANTIQUE’, ‘ANTIQUE005’, ‘Federal Dining Table’, ‘Mahogany two-pillar dining table. Each urn form column rests on three molded sabre legs with brass paws. Two removable leaves are still in place. Excellent condition, minimal wear.’, 4500);
INSERT INTO `inventory` VALUES (‘ELECBOUT’, ‘ELECBT001′, ’32GB High Speed microSD card’, ‘With enough speed for high-speed digital cameras and enough storage space for nearly 50 CDs, this card is perfect for your multimedia devices.’, 123.99);
INSERT INTO `inventory` VALUES (‘ELECBOUT’, ‘ELECBT002’, ‘3-in-1 4GB USB 2.0 Flash Drive Pen and Laser Pointer’, ‘Carry it all in a single device. The bottom is a ball-point pen, the top is a laser pointer, and inside is a 4GB USB flash drive.’, 14.99);
INSERT INTO `inventory` VALUES (‘ELECBOUT’, ‘ELECBT003’, ‘Bluetooth Bracelet with OLED Display’, ‘Pair this bracelet to your bluetooth-enabled phone, and ringtones are a thing of the past. When a call is received, the bracelet vibrates and the incoming caller ID displays on the OLED screen.’, 49);
INSERT INTO `inventory` VALUES (‘ELECBOUT’, ‘ELECBT004’, ‘Fitness Watch with Heart Rate Monitor’, ‘Not only does this device time your workout, it monitors your heart rate. Using ANT+ technology, the device can pair with your exercise equipment or an optional foot pod to track your progress. All of’, 149);
INSERT INTO `inventory` VALUES (‘ELECBOUT’, ‘ELECBT005’, ‘Solar Charging Backpack’, ‘Recharge your phone, mp3 player, or handheld device while on the go with this stylish and roomy backpack. The exterior features a solar cell that charges a built-in rechargeable battery. Connectors ar’, 179.95);

— ——————————————————–


— Table structure for table `store_info`

CREATE TABLE `store_info` (
  `storeID` varchar(10) NOT NULL,
  `name` varchar(50) default NULL,
  `description` varchar(200) default NULL,
  `welcome` text,
  `css_file` varchar(250) default NULL,
  `email_address` varchar(100) default NULL,
  PRIMARY KEY  (`storeID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


— Dumping data for table `store_info`

INSERT INTO `store_info` VALUES (‘COFFEE’, ‘Gosselin”s Gourmet Coffee’, ‘Specialty coffees made from the world”s finest beans’, ‘Welcome to Gosselin”s Gourmet Coffee. Here you will find many of the world”s finest gourmet coffees. Our blends are hand-selected from the most unique and flavorful beans, each custom-roasted to enhance the distinct flavor. Whether you desire a dark, medium or light roast, you will find a special treat on our list.’, ‘GosselinGourmet.css’, ‘ggcoffee@example.com’);
INSERT INTO `store_info` VALUES (‘ANTIQUE’, ‘Old Tyme Antiques’, ‘Furniture from America”s Colonial and Post-war periods’, ‘At Old Tyme Antiques, we search for the finest examples of Early American furniture. Our appraisers and researchers have researched each and every one of our items, and all have a certified provenance. Any restoration work has been performed by our expert restorers, and is fully documented. We are constantly searching estate sales for new items. If you have an item, we would be glad to appraise it for you, or even sell it on consignment.’, ‘OldTymeAntiques.css’, ‘antique1783@example.net’);
INSERT INTO `store_info` VALUES (‘ELECBOUT’, ‘Electronic Boutique’, ‘Computer accessories and peripheral devices’, ‘Want the coolest high-tech gadgets around? You”ve come to the right place. We offer USB drives, media cards, and other electronic devices to enhance your digital life.’, ‘ElectronicsBoutique.css’, ‘usb4sale@example.org’);

Use PHP create an program an online order form–continue

Use PHP create  an program an online order form

you could see what it look like,

http://www.sandywebdesigner.com/index.php?section=Final-Project

http://www.sandywebdesigner.com/con_str/stores/GosselinGourmetCoffee.php

http://www.sandywebdesigner.com/con_str/stores/OldTymeAntiques.php

http://www.sandywebdesigner.com/con_str/stores/ElectronicsBoutique.php

the 3 order form just use the same class, you don’t to rewrite it, just change the storeID, you could use for any shopping cart.

the following post i will write the source code.

Serialization Functions

When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep() (with two leading underscores), which you can use to perform many of the same tasks as a destructor function. However, because a
destructor function is always called when a script that instantiates an object of a class ends,you do not need to duplicate any functionality between a destructor function and the __sleep() function. The primary reason for including a __sleep() function in a class is to specify which data members of the class to serialize. If you do not include a __sleep() function in your class, the serialize() function serializes all of its data members.

You don’t necessarily have to serialize every data member in a class, particularly for large objects that contain numerous data members. If you do include a __sleep() function in your class, the function must return an array of the data members to serialize or you will receive
an error.

Although the destructor function is always called, a constructor function is only called when you instantiate a new class object. This means that when you use the unserialize() function to restore a serialized class object, the constructor function does not execute. However,
when the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup() (with two leading underscore characters), which you can use to perform many of the same tasks as a constructor function. You use the __wakeup() function to perform any initialization the class requires when the object is restored. A typical use of the __wakeup() function is to initialize data members that were not saved with the serialization process, if there are any. Another use of the __wakeup() function is to restore any database or fi le connections that were lost during object serialization.

Cleaning Up with Destructor Functions

A destructor function is commonly called in two ways: when a script ends or when you manually
delete an object with the unset() function. You generally do not need to use a destructor function, although many programmers use one to close previously opened fi le handles and database connections. To add a destructor function to a PHP class, create a function named
__destruct() (with two leading underscore characters). Th e following code contains a destructor function that closes the database connection opened with the constructor function:
function __construct() {
$DBConnect = new mysqli(“php_db”, “dongosselin”,
“rosebud”, “real_estate”)
}
function __destruct() {
$DBConnect->close();
}

Initializing with Constructor Functions

A constructor function is a special function that is called automatically when an object from a
class is instantiated. You defi ne and declare constructor functions the same way you defi ne other functions, although you do not include a return type because constructor functions do not return values. Each class defi nition can contain its own constructor function, named either __construct() (with two leading underscore characters) or the same name as the class.