Jump to content

Recommended Posts

Hi, here's my problem. I'm building a simple buying website and I want the subtotal (before taxes) to be displayed for all the items the shoppers checks that from the bellPublicHome.php and that will be displayed in a subtotal text field when the shopper clicks the Proceed to checkout button.  :rtfm:

 

bellPublicHome.php:

<?php 
  include_once('config.php');
  require 'bellConnect.inc.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bell Mobility by Andy 2: Public</title>
</head>

<body>
<form method="POST" action="buy.php"><?php
$result=mysql_query("SELECT ID, Image, Name, Manufacturer, Price, Description, SimSupport FROM bellProducts");
    //phpinfo(); 

    //NB: print table headings
    if(mysql_num_rows($result))//if there is at least one entry in bellProducts, make a table
    {
        //$counter+=1;
        print "<table border='border'>";
        print "<tr>     
        <th>Select products to buy</th> 
        <th>Image</th> 
        <th>Name</th>
        <th>Manufacturer</th>
        <th>Price</th>
        <th>Description</th>
        <th>Sim Support</th>
        <th>IMEI</th>    
           </tr>";

        //NB: now output each row of records
        while($row=mysql_fetch_assoc($result))//NB: while the current db table's row still has fields to extract 
        {
            //extract($row);
            
                print
                "<tr align='center'>
              
                    <td><input type='checkbox' name='modifyArray[]' value='$row[iD]' id=\"modifyArray[]\" /></td>
                    <td>";
                    if(!empty($row['Image']))
                    {
                        $curImage=$row['Image'];
                    }
                    else if(empty($row['Image']))
                    {
                        $curImage='fileUploadIcon.jpg';
                        //$title="please upload item image";
                    }
                       print "<img src=$curImage width='70px' height='90px' title='please upload product image' />
                    </td>
                    <td> $row[Name] </td>
                    <td> $row[Manufacturer] </td>
                    <td> $$row[Price]</td>
                    <td align='left'>$row[Description]</td>
                    <td>$row[simSupport]</td>
                     <td></td>
                   
                  </tr>";
            //}//END INNER IF
        }//END WHILE
             
  }//END BIG IF

?>
         
</table>
<input type='submit' value='Proceed to checkout' name='checkout' />
    </form>

</body>
</html>

 

buy.php

<?php 
  include_once('config.php');
  require 'bellConnect.inc.php';
?>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bell Mobility by Andy 2: Checkout</title>
</head>
   
<body>

<p><a href="http://localhost/bell/bellPublicHome.php"><img src="Bell_Logo.jpg"/></a></p>

<a href="http://localhost/bell/bellPublicHome.php">Return Home</a>

<hr />

<form method="POST" action=""><!--NB: form starts here b/c of the checkboxes in the html table of checked out itms-->

<?php
//START BIGGEST IF which displays user form when @ least 1 item checked 
if($_POST['checkout'] && !empty($_POST['modifyArray']))//NB: why don't I need isset for $_POST['checkout']
{  
  $idpost = $_POST['modifyArray'];//NB: stores the bellProducts db table ID values for each checked checkbox
  $joincom="";
  
foreach($idpost as $tmpIdpost) 
{
    $joincom.=$tmpIdpost.",";//NB: concatentates all the checked checkboxes values which is the ID  
}

  $tmpIdpost  = $joincom;//NB: make $tmpIdpost store the $joincom string 
$tmpIdpost = substr($tmpIdpost, 0, strlen($tmpIdpost)-1); //NB: remove the last concatenated string: ","

//NB:$joincom concatenates all the ID's stored in the checked checkboxes and that is used in the SQL cmd ...WHERE
//  ID IN (5,6,77 etc.) 	  
  $result=mysql_query("SELECT ID, Image, Name, Manufacturer, Price, Description, SimSupport FROM bellProducts WHERE ID IN ($tmpIdpost);");
  //phpinfo(); 

  echo "<br />";

  echo "<span>Your checked out items below.</span>";
  
  //NB: print table headings
  if(mysql_num_rows($result))//if there is at least one entry in bellProducts, make a table
  {
    print "<table border='border'>";
    print "<tr>       
        <th>Image</th>
        <th>Select items to remove</th>
        <th>Name</th>
        <th>Manufacturer</th>
        <th>Price</th>
        <th>Description</th>
        <th>SimSupport</th>
           </tr>";

        // NB: now output each row of records
        while($row=mysql_fetch_assoc($result))
        {
            //extract($row);
            
                print
                "<tr align='center'>        
                    <td>";
                    if(!empty($row['Image']))
                    {
                        $curImage=$row['Image'];
                    }
                    else if(empty($row['Image']))
                    {
                        $curImage='fileUploadIcon.jpg';
                        //$title="please upload item image";
                    }
                       print "<img src=$curImage width='70px' height='90px' title='please upload product image' />
                    </td>
                    <td><input type='checkbox' name='cartArray' value=$row[iD] /></td>
                    <td> $row[Name] </td>
                    <td> $row[Manufacturer] </td>
                    <td> $$row[Price]</td>
                    <td align='left'>$row[Description]</td>
                    <td>$row[simSupport]</td>
                   
                  </tr>";
            //}//END INNER IF
        }//END WHILE
             
    }//END BIG IF
?>
                   
</table>

<p><input type="submit" value="Remove from cart" /></p>
<br />
<span><strong> - YOUR TOTAL - </strong></span>

<?php 
  //NB: first collect all the IDs of the entries that we want to get prices from 
  $checkedOff=$_POST["modifyArray"];
  $curSubTot=0;
  $joinIDs="";
  foreach($checkedOff as $tmpCheckedOff)
  {
    $joinIDs.=$tmpCheckedOff.",";
  }
  
  $joinIDs=substr($joinIDs,0,strlen($joinIDs)-1);
  $query1=mysql_query("SELECT SUM( ROUND(Price,2) ) FROM bellProducts WHERE ID IN ($joinIDs)");
  $result1=mysql_fetch_assoc($query1);
   
?>
  
  <div style='border-top: 2px solid black; padding-top: 7px;'>
    Sub Total: <input type='text' name='subtotalCost' size='10' style='background-color: #9cf; font-weight: bold;' value=<?php $result1?>/>
    Tax: <input type='text' name='tax' size='10' style='background-color: #9cf' />
    Total: <input type='text' name='totalCost' size='10' style='background-color: #9cf' />
  </div>  

<br /><br />
<hr />
<br />

<p>Please fill in mandatory fields indicated by <span style="color: rgb(255,0,0)">*</span>.</p>

<p>
  <span style="color: rgb(255,0,0)">*</span>Name: <input type='text' name='shopperName' /><input type="hidden" value="<?php echo $idpost;?>" name="iditem"/>
  <span style="color: rgb(255,0,0)">*</span>Email: <input type='text' name='email' />
</p>

<p>
  <span style="color: rgb(255,0,0)">*</span>Address:<input type='text' name='address' />
  <span style="color: rgb(255,0,0)">*</span>Telephone No: <em>(please enter only the digits)</em><input type='text' name='telephone' size='10' maxlength='10'/>
</p>

<p>Alternate telephone No:<input type='text' name='alternateTelephone' size='10' maxlength='10'/></p>

<p>
  <span style="color: rgb(255,0,0)">*</span>City<input type='text' name='city' size='15' maxlength='15'/>
  <span style="color: rgb(255,0,0)">*</span>Province <em></em> <input type='text' name='province' size='3' maxlength='3'/>
</p>

<p>Hobbies & Interests <em>(Hold CTRL to select multiple items)</em> </p>
  <p>
    <select name='hobbiesInterests' size='3'>
      <option>Food</option>
      <option>Shopping</option>
      <option>Sports</option>
      <option>Movies</option>
      <option>Technology</option>
    </select>
  </p>
</p>

<hr />

<p><span style="color: rgb(255,0,0)">*</span>Payment Method<p/>

  <p>
    <img src='amexLogo.jpg' height='20px' width='40px' title='Amex'/><label><input type='radio' value='amex' name='creditCard' checked='checked' /></label>
    <img src='mcLogo.png' height='20px' width='40px' title='Master Card' /><label><input type='radio' value='mc' name='creditCard' /></label>
    <img src='visaLogo.png' height='20px' width='40px' title='Visa' /><label><input type='radio' value='visa' name='creditCard' /></label>
  </p>
    
  <p>
    Credit Card Number: <input type='text' name='creditCardNum' />
    Expiry Date - Month:<input type='text' size='2' maxlength='2' name='ccMonth' /> Year <input type='text' size='2' maxlength='2' name='ccYr'>
  </p>

  <p><strong>- OR -</strong></p>
  <p><img src='payPalLogo.gif' height='20px' width='40px' title='PayPal'/>PayPal - User name:<input type='text'></p>

<hr />

<input type='submit' value='BUY' name='buyNow' />
<input type='reset' value='Reset Order Form' name='resetOrderForm' />
    </form>
       
<?php }//END BIGGEST IF to only show user form if @ least one item checked

else
  echo "You have not selected any items to purchase. 
  {
    <a href='http://localhost/bell/bellPublicHome.php' >Press here to return home.</a>
  }"; 
?>

<?php 
  //NB: validate email and telephone (only shows iff there is @ least one itm selected else no user form
  //  and no validation obviously
  if(isset($_POST['buyNow']))
  {
    $creditCardNum=$_POST['creditCardNum'];
    $creditCardMonth=$_POST['ccMonth'];
    $creditCardYear=$_POST['ccYr'];
    $userAddress=$_POST['address'];
    $userCity=$_POST['city'];
    $userProvince=$_POST['province'];
    $userName=$_POST['shopperName'];
    $userEmail=$_POST['email'];//NB: $POST array stores field value 
    $userTelephone=$_POST['telephone'];
    $emailSyntax=preg_match("/[a-zA-Z0-9]+\@[a-zA-Z0-9]+\.[a-zA-Z]+/", $userEmail);
    $telephoneSyntax=preg_match("/[0-9]{10}/", $userTelephone);
    $creditCardNumSyntax=preg_match("/[0-9]{16}/", $creditCardNum);
    $creditCardMonthSyntax=preg_match("/[0]{1}[1-9]{1}|[1]{1}[0-9]{1}/", $creditCardMonth);
    $creditCardYrSyntax=preg_match("/[1-9]{1}[1-9]{1}/", $creditCardYear);
    
    //NB: how to check if credit card month and year is GREATER THAN OR EQUAL TO today's date???

    if($userName && $emailSyntax && $telephoneSyntax && $userAddress
      && $userCity && $userProvince && $creditCardNumSyntax && $creditCardMonthSyntax &&
      $creditCardYrSyntax)//NB: if shopper fills in all required fields and filled in validly
    {
      $iditem=explode(",", $_POST['iditem']);

      //print($_POST['iditem']);
      $result=mysql_query("INSERT INTO users (name, email) VALUES ('$userName', '$userEmail')");
      $usid = mysql_insert_id();

      foreach($iditem as $iditemed)
      {  
        mysql_query("INSERT INTO purchase (usid, prdid) VALUES ('$usid', '$iditemed')");
      }	 
    
      redirect(DOMAIN."/success.php");
      exit;
    }
    else if(!$userName || !$userProvince || !$userCity || !$userAddress)
      echo "Please ensure all fields are entered.";
    else if(!$emailSyntax && !$telephoneSyntax)
      echo "Please enter a valid emaild address and valid telephone number and make sure all
        required fields are filled in.";  
    else if(!$telephoneSyntax)
        echo "Please enter a valid telephone number and make sure all
          required fields are filled in.";
    else if(!$emailSyntax)
        echo "You entered. $userEmail. .Please enter a valid email address and make sure all
          required fields are filled in.";
    else if(!$creditCardNumSyntax || !$creditCardMonthSyntax || !$creditCardYrSyntax)
    {
        echo "Please enter valid credit card information and make sure all required fields are filled in 
          properly.";
    }
    
  }//END BIG IF buyNow submit button
  
?> 
</body>
</html>


**Actually I figured it out, I had to use mysql_fetch_row($query1) instead of mysql_fetch_assoc($query1) for the script buy.php, BUT I'm curious why I can't use mysql_fetch_assoc)($query1). I tried to do this in buy.php:

 

<?php 
  //NB: first collect all the IDs of the entries that we want to get prices from 
  $checkedOff=$_POST["modifyArray"];
  $curSubTot=0;
  $joinIDs="";
  foreach($checkedOff as $tmpCheckedOff)
  {
    $joinIDs.=$tmpCheckedOff.",";
  }
  
  $joinIDs=substr($joinIDs,0,strlen($joinIDs)-1);
  $query1=mysql_query("SELECT SUM( ROUND(Price,2) ) FROM bellProducts WHERE ID IN ($joinIDs)");
  $result1=mysql_fetch_row($query1);
  echo $result1[0];
?>

 

**why can't I use instead:

$result1=mysql_fetch_assoc($query1) 
echo $result1['Price'];

**is it b/c it doesn't make sense to show the price when I am requesting an SQL sum. Let me know, thanks.

because the key its being stored as in the associative array is 'SUM( ROUND(Price,2) )' I believe. You could use the as operator to make it store in your own defined key name, so

$query1=mysql_query("SELECT SUM( ROUND(Price,2) ) as PriceSum FROM bellProducts WHERE ID IN ($joinIDs)");

 

then you could access it like

$result1['PriceSum']

Hi, that makes sense to use a temporary field name since I am using SELECT SUM(ROUND(Price,2)) etc, but now can you help me with the other problem from the original post of this thread, I want to be able to display the sum of all the checked boxes (the Price field) in the subtotal text field.  :rtfm:

Hey, actually I got it to work, all I had to add was a value attribute as so:

 

<html>
<head></head>
<body>
Sub Total: <input type='text' name='subtotalCost' size='10' style='background-color: #9cf; font-weight: bold;' value=<?php echo '$'.$result1[0]; ?> />
</body>
</html>
[\code]

OK, new related question, how do I prevent the shopper from editing this subtotal text field, I am tempted to use javascript but since I am working with php, I know it's not good to mix client and server-side scripting languages, respectively, so please help. :rtfm:

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.