Member Avatar for LastMitch

@ardav

Yes, I do have a DB on the server but I don't know how to separate the fruits & vegetables and a few weeks back you wrote an array and it seems like it will be easier to used an array and I think I was wrong. Biim was trying to explain to me how to insert the script which I am still doing. But in a good way I'm getting close to understand how a array works differently.

Member Avatar for LastMitch

@ Biiim,

For the taxes I didn't put it in there but it's the line:

if($sstat == "CT"){$taxx = round($ordertotal * .08875,2);}

It supposed be like the way you wrote it:

if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}else{
//bad value
}
}else{
//$sstat != "CT"
}

but I left it out because it won't complie correctly.

For this script:

$Q = "SELECT product_id,product_cat,product_name,product_price FROM products";
$R = mysql_query($Q);
$foods = array();
while($prod = mysql_fetch_assoc($R)){
$foods[$prod['product_cat']]['items'] = array($prod['product_id'],$prod['product_price']);
}

I put it in

$_SESSION["mthis"] ="";
while($row = mysql_fetch_array($result)){

I appreciate your insight again!

Member Avatar for diafol

@LM - I said I wouldn't comment further, but the monster array is a bit worrying. A relational DB model would be far better:

CATEGORIES

  • cat_id [PK/autoincrement]
  • cat_label [varchar] , e.g. fruit, vegetables, stationary....

CATEGORY_TAX_RATES

  • ctr_id [PK/auotincrement]
  • cat_id [FK/int]
  • rate [float or decimal] (e.g. 8.75)
  • datefrom [date OR int]
  • dateto [date OR int] (NULL = ongoing)

CATEGORY_DISCOUNT_RATES

  • cdr_id [PK/auotincrement]
  • cat_id [FK/int]
  • rate [float or decimal] (e.g. 4.50)
  • datefrom [date OR int]
  • dateto [date OR int] (NULL = ongoing)
  • minimum_amount [float or decimal] (e.g. 30.00)

ITEMS

  • item_id [PK/autoincrement]
  • cat_id [FK/tinyint]
  • item_label [varchar] (e.g. apples, broccoli, paper clips...)
  • item_description [text] (general description of product)
  • item_qty_desc [varchar] (e.g. 10/Bag)
  • item_image [varchar] (path to image)
  • item_status [tinyint] (0=inactive/1=active)

ITEM_PRICING

  • ip_id [PK/autoincrment]
  • item_id [FK/int]
  • price [float or decimal] (e.g. 0.89)
  • datefrom [date OR int]
  • dateto [date OR int] (NULL = ongoing)

OK, so you get the idea. You may find the datefrom and dateto over-the-top if you just intend to keep the current pricing and tax rates - if so - combine the ITEM_PRICING with ITEMS and TAX tables with CATEGORIES - taking out the PKs/FKs and date fields.

You will need shipping, users, and orders tables and possibly a separate basket table.

Anyway, feel free to totally ignore this if you want to stick with the array method.

commented: I didn't ignore what you wrote, I'm taking notes +0

@Biiim
I'm loathe to make a comment on this thread as you've been extremely patient and helpful - so will let you get on with it. I just hope that you get a shedload of rep points. All power to you!

haha thanks, i feel like i hijacked it from you initially

@LastMitch

I'll just look through the full page you posted and try get my head around it

Member Avatar for LastMitch

@Biiim

I'll make the script shorter:

<?php
session_start();
header("Cache-control: private");
require_once ('include/init.php');

if (isset($_POST['ins'])) {
if (!isset($_POST['promo'])) {$promo="no";} else {$promo="yes";}

$sstat = $_POST["stat"];

$sql="INSERT INTO cust(fname, lname, email, addr, city, stat, zip, promo, phone, dt, country) VALUES (".
  "'".mysql_real_escape_string(trim($_POST["fname"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["lname"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["email"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["addr"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["city"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["stat"]))."', ".
  "'".mysql_real_escape_string(trim($_POST["zip"]))."', ".
  "'".$promo."', ".
  "'".mysql_real_escape_string(trim($_POST["phone"]))."',NOW(),'".trim(mysql_real_escape_string($_POST["country"]))."') ";

$rs= mysql_query($sql);

$uid = mysql_insert_id();
$_SESSION['uid'] = $uid;

$country = trim($_POST["country"]);
$_SESSION['country'] = trim($_POST["country"]);

if (mysql_affected_rows()<0){
    print "<B>Fatal ERROR: Could not add customer.</B>";
    exit();
}};
        if (isset($_POST['place'])) {   

           $sql="SELECT * from cust where id = ".mysql_real_escape_string($_SESSION['uid']);
           $rs= mysql_query($sql) ;
           echo mysql_error();
           $row=mysql_fetch_array($rs);
           $eemail = $row["email"];
           $country = $row["country"];

          if ($_POST["express"] == "15"){$express = 15; $expyes = "yes";}else{$express = 0; $expyes = "no";}
          if ($_POST["gift_wrap"] == "5"){$gift_wrap = 5; $giftyes = "yes";}else{$gift_wrap = 0; $giftyes = "no";}

          $ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;

          $_SESSION["mthis"] ="" ;
          $_SESSION["mthis"] .=$row["fname"]." ".$row["lname"]."\n" ;
          $_SESSION["mthis"] .=$row["addr"]."\n".$row["city"].", ".$row["stat"].", ".$row["zip"].", "."\n" ;
          $_SESSION["mthis"] .=$row["country"]."\n".$row["email"]."\n".$row["phone"]."\n"."\n"."Order info:"."\n" ;

          $sql="INSERT INTO orders(cust_id, cart_total, taxx, shipping, express, gift_wrap, s_first, s_last, s_addr, s_city, s_stat, s_zip, s_email, s_country, dt, s_phone) VALUES (".
          "'".mysql_real_escape_string($row["id"])."', ".
          "'".mysql_real_escape_string($ordertotal)."', ".
          "'".mysql_real_escape_string($_SESSION["taxx"])."', ".
          "'".mysql_real_escape_string($_SESSION["ship"])."', ".
          "'".mysql_real_escape_string($expyes)."', ".
          "'".mysql_real_escape_string($giftyes)."', ".
          "'".mysql_real_escape_string($row["fname"])."', ".
          "'".mysql_real_escape_string($row["lname"])."', ".
          "'".mysql_real_escape_string($row["addr"])."', ".
          "'".mysql_real_escape_string($row["city"])."', ".
          "'".mysql_real_escape_string($row["stat"])."', ".
          "'".mysql_real_escape_string($row["zip"])."', ".
          "'".mysql_real_escape_string($row["email"])."', ".
          "'".mysql_real_escape_string($row["country"])."',NOW(),'".mysql_real_escape_string($row["phone"])."') ";

$rs= mysql_query($sql,$o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

          $oid = mysql_insert_id();

          $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");

            if (mysql_num_rows($result)==0){
            echo mysql_num_rows($result);}
            while($row = mysql_fetch_array($result)){

             $_SESSION["mthis"] .=$row["itemName"]."\n" ;
             $_SESSION["mthis"] .="itemNumber: ".$row["itemNumber"]."\n" ;
             $_SESSION["mthis"] .="Qty: ".$row["qty"]."\n" ;    
             $_SESSION["mthis"] .="gift_wrap: ".ucwords($row["gift_wrap"])."\n" ;
             $_SESSION["mthis"] .="Unit Price: ".$row["price"]."\n"."\n" ;  

             $sql="INSERT INTO order_details(o_id, prod_id, name, itemNumber, qty, gift_wrap, unitprice, total) VALUES (".
              "'".mysql_real_escape_string($oid)."', ".
              "'".mysql_real_escape_string($row["itemId"])."', ".
              "'".mysql_real_escape_string($row["itemName"])."', ".
              "'".mysql_real_escape_string($row["itemNumber"])."', ".
              "'".mysql_real_escape_string($row["qty"])."', ".
              "'".mysql_real_escape_string($row["gift_wrap"])."', ".
              "'".mysql_real_escape_string($row["price"])."', ".
              "'".mysql_real_escape_string($row["price"]*$row["qty"])."') ";      
$rs= mysql_query($sql, $o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
            }

            $_SESSION["mthis"] .="Shipping = $ ".$_SESSION["ship"]."\n" ;
            $_SESSION["mthis"] .="Express Shippig = $ ".$expyes."\n" ;
            $_SESSION["mthis"] .="gift_wrap = $ ".$giftyes."\n" ;
            if ($taxx != ""){$_SESSION["mthis"] .="Tax = $ ".$taxx."\n" ;}  
            $_SESSION["mthis"] .="Total = $ ".$ordertotal."\n" ;    
            $_SESSION["mthis"] .="........................................"; 
                }
        ?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <style type="text/css"> 
         <!--
        .style1 {font-family: "Times New Roman", Times, serif; font-size: 12px;color: #333333;}
        .style5 {color: #FFFFFF}
        .style8 {font-size: 10px}
         --> 
         </style>
        <script language="javascript">
        function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + '$' + num + '.' + cents);
        }

        function calcFees(chk,cost){if (chk.checked == 1){
            document.getElementById("stotal").innerHTML = formatCurrency(cost + 15);} else{
            document.getElementById("stotal").innerHTML = formatCurrency(cost);}}
        function calcFees1(chk,cost){if (chk.checked == 1){
            document.getElementById("stotal").innerHTML = formatCurrency(cost + 5);} else{ 
            document.getElementById("stotal").innerHTML = formatCurrency(cost);}}
        </script>
</head>
    <body>
                              <? include("header.php");?>
<table width="800" height="298" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#FFFFFF">
  <tr>
    <td height="298" align="center" valign="top"><p><a href="index_09.html"></a></p>
        <table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
          <tr>
            <td width="200" height="25" align="center"><h3 align="center" class="style17">CHECKOUT </h3>
                <p align="center" class="style1">Please verify the info <strong></strong> belo<span class="style42">w</span>: <br>
                    <br>
              </p></td>
          </tr>
        </table>
      <div align="center">
          <form action="checkout2.php?" method="post">
<?php
    function GetCartId(){
        // This function will generate an encrypted string and
        // will set it as a cookie using set_cookie. This will
        // also be used as the cookieId field in the cart table
        if(isset($_COOKIE["cartId"])){
            return $_COOKIE["cartId"];}
        else{
            // There is no cookie set. We will set the cookie
            // and return the value of the users session ID
            session_start();
            setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
            return session_id();}}

    $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");
 ?>
            <table width="78%" border="0" align="center" cellpadding="3" cellspacing="0" bgcolor="#CCCCCC">
              <tr>
                <td width="15%" height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">ITEM NUMBER</span></td>
                <td height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">ITEM</span></td>
                <td height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">QTY</span></td>
                <td height="25" bgcolor="#999999" class="style1"><span class="style34 style37 style17 style5 style8">SUBTOTAL</span></td>
              </tr>
              <? 
if (mysql_num_rows($result)==0){
echo mysql_num_rows($result);
    }
$_SESSION["mthis"] ="";
while($row = mysql_fetch_array($result)){
// Increment the total cost of all items
$foods = array();
$totalCost += ($row["qty"] * $row["price"]);
$ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;

if($sstat == "CT"){$taxx = round($ordertotal * .08875,2);}

    function listItems($input){
    //CONFIG ARRAY
    $foods = array(
    "fruit"=> array("items"=>array(
    //Fruit--------------------
    //Apple----------
    //Cortland
    'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
    //Ginger Gold 
    'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75, 
    //Idared
    'A-I01'=>35, 'A-I02'=>50, 'A-I03'=>75, 
    //McIntosh
    'A-M01'=>35, 'A-M02'=>50, 'A-M03'=>75, 
    )),

    "vegetable"=> array("items"=>array(
    //Vegetable--------------------
    //Asparagus
    'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80, 
    //Broccoli
    'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80, 
    //Carrots
    'C-A01'=>35, 'C-C02'=>55, 'C-C03'=>80, 
    //Celery
    'C-E01'=>35, 'C-E02'=>55, 'C-E03'=>80, 
    //Cucumber
    'C-U01'=>35, 'C-U02'=>55, 'C-U03'=>80,  
    )) );
     //VARIABLES
    $running = array('fruit'=>0,'vegetable'=>0);
    $output = array('fruit'=>'','vegetable'=>'');
    $tax = array('fruit'=>0,'vegetable'=>0);
    //LOOP THROUGH INPUT
    foreach($input as $item){
    $key = $item[0];
    $qty = $item[1];
    if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
    $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
    $unit = $foods[$type]['items'][$key];
    $cost = number_format($qty * $unit,2);
    $output[$type] .= "<tr><td>$key</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";
    $running[$type] += $cost;
    }}
    //DO TOTALS FOR OUTPUT
    //1) Tax
    if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
    $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
    $fruit_tax_label = $foods['fruit']['tax_ex_rate'] . "%";
    }else{
    $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
    $fruit_tax_label = $foods['fruit']['tax_rate'] . "%";
    }
    if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
    $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
    $vegetable_tax_label = $foods['vegetable']['tax_ex_rate'] . "%";
    }else{
    $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
    $vegetable_tax_label = $foods['vegetable']['tax_rate'] . "%";
    }
    $total_tax = $tax['fruit'] + $tax['vegetable'];
    //2) Sales Total
    $total_sales = $running['vegetable'] + $running['fruit'];
    //3) Bill Total
    $total_bill = $total_sales + $total_tax;
    //BUILD TOTAL HTML
    $total =
    "<tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Fruits</td><td class=\"right\">" . number_format($running['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Vegetables</td><td class=\"right\">" . number_format($running['vegetable'],2) . "</td></tr>
    <tr><td colspan=\"3\">Total Sales</td><td class=\"right\">" . number_format($total_sales,2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Fruit Tax @ $fruit_tax_label</td><td class=\"right\">" . number_format($tax['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Vegetable Tax @ $vegetable_tax_label</td><td class=\"right\">" . number_format($tax['vegetable'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Tax</td><td class=\"right\">" . number_format($total_tax, 2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Bill</td><td class=\"right\">" . number_format($total_bill, 2) . "</td></tr>";
    $returndata = array();
    $returndata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
    $returndata['veg_tax_label'] = $vegetable_tax_label;
    $returndata['fruit_tax_label'] = $fruit_tax_label;
    $returndata['totaltax'] = $total_tax;
    $returndata['totalsales'] = $total_sales;
    $returndata['totalbill'] = $total_bill;
    return $returndata;
    }
    //your checkout items need to go in here into $input
    $input = array(
    //Apple---------- 24 per box / 48 per box / 60 per box 
    //Cortland 
    array('A-C01',1),array('A-C02',1),array('A-C03',1),
    //Ginger Gold
    array('A-G01',1),array('A-G02',1),array('A-G03',1),
    //Idared 
    array('A-I01',1),array('A-I02',1),array('A-I03',1),
    //McIntosh 
    array('A-M01',1),array('A-M02',1),array('A-M03',1),)),

    //Vegetable------ 24 per box / 48 per box / 60 per box 
    //Asparagus 
    array('A-A01',1),array('A-A02',1),array('A-A03',1), 
    //Broccoli 
    array('B-B01',1),array('B-B02',1),array('B-B03',1), 
    //Carrots 
    array('C-A01',1),array('C-C02',1),array('C-C03',1), 
    //Celery 
    array('C-E01',1),array('C-E02',1),array('C-E03',1), 
    //Cucumber
    array('C-U01',1),array('C-U02',1),array('C-U03',1), );
    ?>
              <tr>
       <td height="25" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"><?php echo $row["itemNumber"]; ?></font></span></td>
                <td width="57%" height="25" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"> <?php echo $row["itemName"]; ?> - <font face="verdana"><?php echo $row["size"]; ?></font></font></span></td>
            <td width="11%" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"> <?php echo $row["qty"]; ?> </font></span></td>
                <td width="15%" height="25" bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"> $<?php echo number_format($row["price"]*$row["qty"], 2, ".", ","); ?></font></span></td>
              </tr>
              <?php
}

$domestic = array('United States');

if(in_array($_POST['country'],$domestic)){
//----------Domestic Shipping--------------//
if ($totalCost > 0 && $totalCost <= 100){$ship = 6.50;}
if ($totalCost > 100 && $totalCost <= 300){$ship = 10.50;}
if ($totalCost > 300 && $totalCost <= 500){$ship = 14.00;}
if ($totalCost > 500 && $totalCost <= 700){$ship = 18.00;}
if ($totalCost > 700 && $totalCost <= 1000){$ship = 20.00;}
if ($totalCost > 1000){$ship = 25.00;}
}else{
//----------International Shipping--------------//
if ($totalCost > 0 && $totalCost <= 100){$ship = 30.00;}
if ($totalCost > 100 && $totalCost <= 300){$ship = 35.00;}
if ($totalCost > 300 && $totalCost <= 500){$ship = 40.00;}
if ($totalCost > 500 && $totalCost <= 700){$ship = 45.00;}
if ($totalCost > 700 && $totalCost <= 1000){$ship = 50.00;}
if ($totalCost > 1000){$ship = 50.00;} 
}
//----------store important values in session--------------//
    $_SESSION['tcost'] = $totalCost;
    $_SESSION['ship']  = $ship;
    $_SESSION['taxx']  = $taxx;
//----------store important values in session--------------//
?>
              <tr>
                <td colspan="4" bgcolor="#FFFFFF" class="style1"><div align="right">______________________</div></td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">TAX:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"> <font face="verdana"><b>$<?php echo number_format($taxx, 2, ".", ","); ?></b></font></span></td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">SHIPPING:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"> <font face="verdana"><b>$<?php echo number_format($ship, 2, ".", ","); ?></b></font></span></td>
              </tr>
              <tr>
         <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">* EXPRESS DELIVERY: </span></div></td>
         <td bgcolor="#FFFFFF" class="style1"><input name="express" type="checkbox" id="express" onClick="calcFees(express,<?=$totalCost + $ship + $taxx;?>);" value="15"/>
                </td>
              </tr>
              <tr>
            <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">GiFT WRAP ($5): </span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><input name="gift_wrap" type="checkbox" id="gift_wrap" onClick="calcFees1(gift_wrap,<?=$totalCost + $ship + $taxx;?>);" value="5"/>
                </td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">TOTAL:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"><b>
                  <div id="stotal">$<?php echo number_format($totalCost + $ship + $taxx, 2, ".", ","); ?></div>
                </b></font></span></td>
              </tr>
            </table>
            <p class="navtitlesm"><strong>* Express Delivery</strong><br>
  For an additional $20, Express orders placed by 9 am ET will be delivered in  the contiguous U.S.<br> 
  in 2 business days for most in-stock.&nbsp;</p>
            <p align="center">
              <input name="place" type="hidden" id="place" value="yes" />
              <input name="tcost" type="hidden" id="tcost" value="<? echo $totalCost; ?>" />
              <input name="ship" type="hidden" id="ship" value="<? echo $ship; ?>" />
              <input name="taxx" type="hidden" id="taxx" value="<? echo $taxx; ?>" />
              <input type="submit" name="Submit" value="Place Order" />
            </p>
          </form>
    </div></td>
  </tr>
</table>
                              <? include("footer.php");?>                       
</body>
</html>
Member Avatar for LastMitch

@ Biiim,

i apologizes for not making the script clear to see the issue

I would suggest to keep conditions and slab in mysql table rather than php.

How does this work for you?

<?php
session_start();
header("Cache-control: private");
require_once ('include/init.php');
require_once ('include/functions.php');

if (isset($_POST['ins'])) {
    if (!isset($_POST['promo'])) {$promo="no";} else {$promo="yes";}

    $sstat = $_POST["stat"];
    $sql="INSERT INTO cust(fname, lname, email, addr, city, stat, zip, promo, phone, dt, country) VALUES (".
      "'".mysql_real_escape_string(trim($_POST["fname"]))."', ".
      "'".mysql_real_escape_string(trim($_POST["lname"]))."', ".
      "'".mysql_real_escape_string(trim($_POST["email"]))."', ".
      "'".mysql_real_escape_string(trim($_POST["addr"]))."', ".
      "'".mysql_real_escape_string(trim($_POST["city"]))."', ".
      "'".mysql_real_escape_string(trim($_POST["stat"]))."', ".
      "'".mysql_real_escape_string(trim($_POST["zip"]))."', ".
      "'".$promo."', ".
      "'".mysql_real_escape_string(trim($_POST["phone"]))."',NOW(),'".trim(mysql_real_escape_string($_POST["country"]))."') ";
    $rs= mysql_query($sql);
    $uid = mysql_insert_id();
    $_SESSION['uid'] = $uid;
    $country = trim($_POST["country"]);
    $_SESSION['country'] = trim($_POST["country"]);
    if (mysql_affected_rows()<0){
        print "<B>Fatal ERROR: Could not add customer.</B>";
        exit();
    }
}
if (isset($_POST['place'])) {   
    $sql="SELECT * from cust where id = ".mysql_real_escape_string($_SESSION['uid']);
           $rs= mysql_query($sql) ;
           echo mysql_error();
           $row=mysql_fetch_array($rs);
           $eemail = $row["email"];
           $country = $row["country"];
          if ($_POST["express"] == "15"){$express = 15; $expyes = "yes";}else{$express = 0; $expyes = "no";}
          if ($_POST["gift_wrap"] == "5"){$gift_wrap = 5; $giftyes = "yes";}else{$gift_wrap = 0; $giftyes = "no";}
          $ordertotal = $_SESSION["tcost"] + $_SESSION["ship"] + $_SESSION["taxx"] + $express + $gift;
          $_SESSION["mthis"] ="" ;
          $_SESSION["mthis"] .=$row["fname"]." ".$row["lname"]."\n" ;
          $_SESSION["mthis"] .=$row["addr"]."\n".$row["city"].", ".$row["stat"].", ".$row["zip"].", "."\n" ;
          $_SESSION["mthis"] .=$row["country"]."\n".$row["email"]."\n".$row["phone"]."\n"."\n"."Order info:"."\n" ;
          $sql="INSERT INTO orders(cust_id, cart_total, taxx, shipping, express, gift_wrap, s_first, s_last, s_addr, s_city, s_stat, s_zip, s_email, s_country, dt, s_phone) VALUES (".
          "'".mysql_real_escape_string($row["id"])."', ".
          "'".mysql_real_escape_string($ordertotal)."', ".
          "'".mysql_real_escape_string($_SESSION["taxx"])."', ".
          "'".mysql_real_escape_string($_SESSION["ship"])."', ".
          "'".mysql_real_escape_string($expyes)."', ".
          "'".mysql_real_escape_string($giftyes)."', ".
          "'".mysql_real_escape_string($row["fname"])."', ".
          "'".mysql_real_escape_string($row["lname"])."', ".
          "'".mysql_real_escape_string($row["addr"])."', ".
          "'".mysql_real_escape_string($row["city"])."', ".
          "'".mysql_real_escape_string($row["stat"])."', ".
          "'".mysql_real_escape_string($row["zip"])."', ".
          "'".mysql_real_escape_string($row["email"])."', ".
          "'".mysql_real_escape_string($row["country"])."',NOW(),'".mysql_real_escape_string($row["phone"])."') ";
$rs= mysql_query($sql,$o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
          $oid = mysql_insert_id();
          $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");
            if (mysql_num_rows($result)==0){
            echo mysql_num_rows($result);}
            while($row = mysql_fetch_array($result)){
             $_SESSION["mthis"] .=$row["itemName"]."\n" ;
             $_SESSION["mthis"] .="itemNumber: ".$row["itemNumber"]."\n" ;
             $_SESSION["mthis"] .="Qty: ".$row["qty"]."\n" ;    
             $_SESSION["mthis"] .="gift_wrap: ".ucwords($row["gift_wrap"])."\n" ;
             $_SESSION["mthis"] .="Unit Price: ".$row["price"]."\n"."\n" ;  
             $sql="INSERT INTO order_details(o_id, prod_id, name, itemNumber, qty, gift_wrap, unitprice, total) VALUES (".
              "'".mysql_real_escape_string($oid)."', ".
              "'".mysql_real_escape_string($row["itemId"])."', ".
              "'".mysql_real_escape_string($row["itemName"])."', ".
              "'".mysql_real_escape_string($row["itemNumber"])."', ".
              "'".mysql_real_escape_string($row["qty"])."', ".
              "'".mysql_real_escape_string($row["gift_wrap"])."', ".
              "'".mysql_real_escape_string($row["price"])."', ".
              "'".mysql_real_escape_string($row["price"]*$row["qty"])."') ";      
$rs= mysql_query($sql, $o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
            }
            $_SESSION["mthis"] .="Shipping = $ ".$_SESSION["ship"]."\n" ;
            $_SESSION["mthis"] .="Express Shippig = $ ".$expyes."\n" ;
            $_SESSION["mthis"] .="gift_wrap = $ ".$giftyes."\n" ;
            if ($taxx != ""){$_SESSION["mthis"] .="Tax = $ ".$taxx."\n" ;}  
            $_SESSION["mthis"] .="Total = $ ".$ordertotal."\n" ;    
            $_SESSION["mthis"] .="........................................"; 
                }
        ?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <style type="text/css"> 
         <!--
        .style1 {font-family: "Times New Roman", Times, serif; font-size: 12px;color: #333333;}
        .style5 {color: #FFFFFF}
        .style8 {font-size: 10px}
         --> 
         </style>
        <script language="javascript">
        function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + '$' + num + '.' + cents);
        }
        </script>
</head>
<body>
    <? include("header.php");?>
    <table width="800" height="298" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#FFFFFF">
        <tr>
            <td height="298" align="center" valign="top">
                <p><a href="index_09.html"></a></p>
                <table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="200" height="25" align="center">
                            <h3 align="center" class="style17">CHECKOUT </h3>
                            <p align="center" class="style1">
                                Please verify the info <strong></strong> belo<span class="style42">w</span>:<br/>
                                <br/>
                            </p>
                        </td>
                    </tr>
                </table>
                <div align="center">
                    <form action="checkout2.php?" method="post">
                        <table width="78%" border="0" align="center" cellpadding="3" cellspacing="0" bgcolor="#CCCCCC">
                        <?php
                            $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");
                            if (mysql_num_rows($result)==0){
                                echo mysql_num_rows($result);
                            }
                            $_SESSION["mthis"] ="";
                            $input = array();
                            while($row = mysql_fetch_array($result)){
                                //loop through all items in the current cart?
                                //$row['itemId'] should match up to the codes in the $foods array
                                $input[] = array($row['itemId'],$row['qty']);
                                //$input[] = array($row['itemId'],5);//test it with just a quantity of 5 for each item
                            }
                            $cartdata = listItems($input,$_POST['country']);

                            //$cartdata['html'] = "<table><tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total . "</table>";
                            //$cartdata['veg_tax_label'];//tax % applied to veg
                            //$cartdata['fruit_tax_label'];//tax % applied to fruit
                            //$cartdata['totaltax'];//actual tax for cart
                            //$cartdata['totalsales'];//sales value without tax
                            //$cartdata['shipping'];//Shipping cost for value of cart
                            //$cartdata['totalbill'];//total value of cart with shipping & tax added

                            $cartTotalCost = $cartdata['totalbill'];
                            $ship = $cartdata['shipping'];
                            $salesTotal = $cartdata['totalsales'];
                            $totalTax = $cartdata['totaltax'];

                            $ordertotal = $cartTotalCost + $express + $gift;
                            //----------store important values in session--------------//
                                $_SESSION['tcost'] = $totalCost;
                                $_SESSION['ship']  = $ship;
                                $_SESSION['taxx']  = $totalTax;
                            //----------store important values in session--------------//
                            echo $cartdata['html']
?>
              <tr>
                <td colspan="4" bgcolor="#FFFFFF" class="style1"><div align="right">______________________</div></td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">TAX:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"> <font face="verdana"><b>$<?php echo number_format($totalTax, 2, ".", ","); ?></b></font></span></td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">SHIPPING:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"> <font face="verdana"><b>$<?php echo number_format($ship, 2, ".", ","); ?></b></font></span></td>
              </tr>
              <tr>
         <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">* EXPRESS DELIVERY: </span></div></td>
         <td bgcolor="#FFFFFF" class="style1"><input name="express" type="checkbox" id="express" onClick="calcFees(this);" value="15"/>
                </td>
              </tr>
              <tr>
            <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">GiFT WRAP ($5): </span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><input name="gift_wrap" type="checkbox" id="gift_wrap" onClick="calcFees(this);" value="5"/>
                </td>
              </tr>
              <tr>
                <td colspan="3" bgcolor="#FFFFFF" class="style1"><div align="right" class="style17 style8"><span class="style39">TOTAL:</span></div></td>
                <td bgcolor="#FFFFFF" class="style1"><span class="style32 style8"><font face="verdana"><b>
                  <div id="stotal">$<?php echo number_format($ordertotal, 2, ".", ","); ?></div>
                </b></font></span>
                <script type='text/javascript'>
                function calcFees(obj,type){
                    if (obj.checked){
                        document.getElementById("stotal").innerHTML = formatCurrency(<?php echo $ordertotal;?> + parseInt(obj.value));
                    }else{
                        document.getElementById("stotal").innerHTML = formatCurrency(<?php echo $ordertotal;?>);
                    }
                }
                </script>
                </td>
              </tr>
            </table>
            <p class="navtitlesm"><strong>* Express Delivery</strong><br>
  For an additional $20, Express orders placed by 9 am ET will be delivered in  the contiguous U.S.<br> 
  in 2 business days for most in-stock.&nbsp;</p>
            <p align="center">
              <input name="place" type="hidden" id="place" value="yes" />
              <?php //The total cost here is the sales cost without tax or shipping? 
              ?>
              <input name="tcost" type="hidden" id="tcost" value="<? echo $salesTotal; ?>" />
              <input name="ship" type="hidden" id="ship" value="<? echo $ship; ?>" />
              <input name="taxx" type="hidden" id="taxx" value="<? echo $taxx; ?>" />
              <input type="submit" name="Submit" value="Place Order" />
            </p>
          </form>
    </div></td>
  </tr>
</table>
                              <? include("footer.php");?>                       
</body>
</html>

i separated some bits out to make the rest of the file more readable:
functions.php

<?php 
function getFoodArray(){
    $foods = array(
    "fruit"=> array("items"=>array(
    //Fruit--------------------
    //Apple----------
    //Cortland
    'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
    //Ginger Gold 
    'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75, 
    //Idared
    'A-I01'=>35, 'A-I02'=>50, 'A-I03'=>75, 
    //McIntosh
    'A-M01'=>35, 'A-M02'=>50, 'A-M03'=>75, 
    //Grapefruit
    'G-001'=>35, 'G-002'=>50, 'G-003'=>75,
    //Lemon
    'L-001'=>35, 'L-002'=>50, 'L-003'=>75,
    //Orange
    'O-001'=>35, 'O-002'=>50, 'O-003'=>75,  
    //Pears 
    'P-001'=>35, 'P-002'=>50, 'P-003'=>75, 
    //Tangerine
    'T-001'=>35, 'T-002'=>50, 'T-003'=>75,   
    //Asian Pears 
    'P-A01'=>55, 'P-A02'=>105, 'P-A03'=>165, 
    //Guava
    'G-V01'=>55, 'G-V02'=>105, 'G-V03'=>165,  
    //Kiwi
    'K-001'=>55, 'K-002'=>105, 'K-003'=>165,  
    //Mango
    'M-001'=>55, 'M-002'=>105, 'M-003'=>165,  
    //Papaya
    'P-P01'=>55, 'P-P02'=>105, 'P-P03'=>165, 
    //Pomegranate
    'P-001'=>55, 'P-002'=>105, 'P-003'=>165,   
    //Star fruit
    'S-001'=>55, 'S-002'=>105, 'S-003'=>165,    
    //Cantaloupe
    'C-001'=>55, 'C-002'=>95, 'C-003'=>120, 
    //Honey Dew
    'H-001'=>55, 'H-002'=>95, 'H-003'=>120, 
    //Watermelon
    'W-001'=>55, 'W-002'=>95, 'W-003'=>120, 
    //Banana
    'B-001'=>35, 'B-002'=>50, 'B-003'=>75, 
    //Lychee
    'L-Y01'=>55, 'L-Y02'=>105, 'L-Y03'=>165,
    //Cranberry 
    'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
    //Raspberry
    'R-B01'=>20, 'R-B02'=>30, 'R-B03'=>50, 
    //Cherry ---------
    //Black 
    'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
    //Chelan
    'C-C01'=>20, 'C-C02'=>30, 'C-C03'=>50, 
    //Sweet Cherry
    'C-S01'=>20, 'C-S02'=>30, 'C-S03'=>50, 
    //Grapes----------
    //Purple
    'G-P01'=>20, 'G-P02'=>30, 'G-P03'=>50, 
    //Red
    'G-R01'=>20, 'G-R02'=>30, 'G-R03'=>50, 
    //White
    'G-W01'=>20, 'G-W02'=>30, 'G-W03'=>50, 
    ),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
    "vegetable"=> array("items"=>array(
    //Vegetable--------------------
    //Asparagus
    'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80, 
    //Broccoli
    'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80, 
    //Carrots
    'C-A01'=>35, 'C-C02'=>55, 'C-C03'=>80, 
    //Celery
    'C-E01'=>35, 'C-E02'=>55, 'C-E03'=>80, 
    //Cucumber
    'C-U01'=>35, 'C-U02'=>55, 'C-U03'=>80,  
    //Eggplant
    'E-P01'=>35, 'E-P02'=>55, 'E-P03'=>80, 
    //Garlic
    'G-L01'=>35, 'G-L02'=>55, 'G-L03'=>80, 
    //Ginger
    'G-G01'=>35, 'G-G02'=>55, 'G-G03'=>80, 
    //Green Bean
    'G-B01'=>35, 'G-B02'=>55, 'G-B03'=>80, 
    //Iceberg Lettuce 
    'I-L01'=>35, 'I-L02'=>55, 'I-L03'=>80, 
    //Lettuce 
    'L-T01'=>35, 'L-T02'=>55, 'L-T03'=>80, 
    //Tomoto
    'T-O01'=>35, 'T-O02'=>55, 'T-O03'=>80, 
    //Potato
    'P-O01'=>35, 'P-O02'=>55, 'P-O03'=>80, 
    //Onion
    'O-N01'=>35, 'O-N02'=>55, 'O-N03'=>80, 
    //Snow pea 
    'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
    //Soybean 
    'S-B01'=>35, 'S-B02'=>55, 'S-B03'=>80,  
    //Spinach
    'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
    //Squash
    'S-Q01'=>35, 'S-Q02'=>55, 'S-Q03'=>80, 
    //Sweet Corn
    'S-C01'=>35, 'S-C02'=>55, 'S-C03'=>80,   
    //Sweet Potato
    'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80,    
    //Chinese Long Beans
    'CH-LB01'=>45, 'CH-LB02'=>90, 'CH-LB03'=>175, 
    //Chinese Kai-lan
    'CH-KL01'=>45, 'CH-KL02'=>90, 'CH-KL03'=>175, 
    //Chinese Pak choy
    'CH-PC01'=>45, 'CH-PC02'=>90, 'CH-PC03'=>175, 
    //Chinese Taro
    'CH-TA01'=>45, 'CH-TA02'=>90, 'CH-TA03'=>175, 
    //Chinese Water Chestnut
    'CH-WC01'=>45, 'CH-WC02'=>90, 'CH-WC03'=>175, 
    //Chinese Winter melon
    'CH-WM01'=>45, 'CH-WM02'=>90, 'CH-WM03'=>175, 
    ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75));
    return $foods;
}
function listItems($input,$ship_country){
    //CONFIG ARRAY
    $foods = getFoodArray();
     //VARIABLES
    $running = array('fruit'=>0,'vegetable'=>0);
    $output = array('fruit'=>'','vegetable'=>'');
    $tax = array('fruit'=>0,'vegetable'=>0);
    //LOOP THROUGH INPUT
    foreach($input as $item){
        $key = $item[0];
        $qty = $item[1];
        if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
            $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
            $unit = $foods[$type]['items'][$key];
            $cost = number_format($qty * $unit,2);
            $output[$type] .= "<tr><td>$key</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";
            $running[$type] += $cost;
        }
    }
    //DO TOTALS FOR OUTPUT
    //1) Tax
    if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
        $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
        $fruit_tax_label = $foods['fruit']['tax_ex_rate'] . "%";
    }else{
        $tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
        $fruit_tax_label = $foods['fruit']['tax_rate'] . "%";
    }
    if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
        $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
        $vegetable_tax_label = $foods['vegetable']['tax_ex_rate'] . "%";
    }else{
        $tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
        $vegetable_tax_label = $foods['vegetable']['tax_rate'] . "%";
    }

    $total_tax = $tax['fruit'] + $tax['vegetable'];
    //2) Sales Total
    $total_sales = $running['vegetable'] + $running['fruit'];
    //3) Shipping
    $domestic = array('United States');
    if(in_array($ship_country,$domestic)){
        //----------Domestic Shipping--------------//
        if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
        if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
        if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
        if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
        if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
        if ($total_sales > 1000){$ship = 25.00;}
    }else{
        //----------International Shipping--------------//
        if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
        if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
        if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
        if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
        if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
        if ($total_sales > 1000){$ship = 50.00;}
    }
    //4) Bill Total
    $total_bill = $total_sales + $total_tax + $ship;
    //BUILD TOTAL HTML
    $total =
    "<tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Fruits</td><td class=\"right\">" . number_format($running['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Vegetables</td><td class=\"right\">" . number_format($running['vegetable'],2) . "</td></tr>
    <tr><td colspan=\"3\">Total Sales</td><td class=\"right\">" . number_format($total_sales,2) . "</td></tr>
    <tr><td colspan=\"3\">Shipping Cost</td><td class=\"right\">" . number_format($ship,2) . "</td></tr>

    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Fruit Tax @ $fruit_tax_label</td><td class=\"right\">" . number_format($tax['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Vegetable Tax @ $vegetable_tax_label</td><td class=\"right\">" . number_format($tax['vegetable'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Tax</td><td class=\"right\">" . number_format($total_tax, 2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Bill</td><td class=\"right\">" . number_format($total_bill, 2) . "</td></tr>";
    $returndata = array();
    $returndata['html'] = "<tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total;
    $returndata['veg_tax_label'] = $vegetable_tax_label;
    $returndata['fruit_tax_label'] = $fruit_tax_label;
    $returndata['shipping'] = $ship;
    $returndata['totaltax'] = $total_tax;
    $returndata['totalsales'] = $total_sales;
    $returndata['totalbill'] = $total_bill;
    return $returndata;
}
function GetCartId(){
    // This function will generate an encrypted string and
    // will set it as a cookie using set_cookie. This will
    // also be used as the cookieId field in the cart table
    if(isset($_COOKIE["cartId"])){
        return $_COOKIE["cartId"];
    }else{
        // There is no cookie set. We will set the cookie
        // and return the value of the users session ID
        session_start();
        setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
        return session_id();
    }
}

The mysql puzzles me a bit, select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc The contents of the users basket is stored in mysql?

commented: Good Example of how the array works in php +2

i apologizes for not making the script clear to see the issue

It's ok its what you're working with - i'm just doing other things as well.

I'd rather help you understand it than just write it, once you understand it you're on your way again rather than being confused waiting for us to reply.

hopefully the way i've written it will help understand it better, the arrays the function uses are quite complex to get your head around and on top of that theres the shopping cart which are usually quite complex. I've done quite a few projects where i've had to jump into someone elses code and i've seen worse haha

commented: Thanks for being patience! +0
Member Avatar for LastMitch

Hi Biiim,

Thanks for the new outline of the script. I'll read it and complied it and see how it looks like.
I appreciated that you'll taking your time to created that file to help me understand how the array works. I'll get back to you once I'll read it closer. Thanks again.

Member Avatar for LastMitch

@Biiim

I went through the scripts and it works! The array match up to the functions.php! I still have a few more things to modify.

I can't seem to figure out how to put the ItemName?

You wrote:

$input[ ] = array($row['itemId'],$row['qty']);

$output[$type] .= "<tr><td>$key</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";

I try to put $row['itemName'] into the $input[ ] = array and it push the $output out of reach meaning I can't see the data.

I also realized that you change my calcFee function:

function calcFees(chk,cost){if (chk.checked == 1){
document.getElementById("stotal").innerHTML = formatCurrency(cost + 15);} else{
document.getElementById("stotal").innerHTML = formatCurrency(cost);}}
function calcFees1(chk,cost){if (chk.checked == 1){
document.getElementById("stotal").innerHTML = formatCurrency(cost + 5);} else{
document.getElementById("stotal").innerHTML = formatCurrency(cost);}}

into

function calcFees(obj,type){
if (obj.checked){
document.getElementById("stotal").innerHTML = formatCurrency(<?php echo $ordertotal;?> + parseInt(obj.value));
}else{
document.getElementById("stotal").innerHTML = formatCurrency(<?php echo $ordertotal;?>);
}
}

I be honest with you, the way you wrote is the correct way!

The 'shipping country' looks the same, the only difference you change

$_POST['country']

As for state:

if($sstat == "CT"){$totalTax = round($total) ? Is this right>?

I mean the I got no idea how you manage to configure the functions.php and with the checkout.php but it came very good, all of the arrays on functions.php match up with the arrays on db.

So the fruit taxes and vegetable taxes are separated. I just need to know how to make 'CT' state (crown colony) as default for the to Total Tax.

I appreciate your insight again!

woo progress!

A quick way i can think of to get the food names is to make another array to translate the food id to its name

<?php
function getFoodKeyArray(){
    $foods = array(
        //Cortland
        'A-C01'=>'Cortland Apple 35', 'A-C02'=>'Cortland Apple 50', 'A-C03'=>'Cortland Apple 75',
        //Ginger Gold 
        'A-G01'=>'Ginger Gold 35', 'A-G02'=>'Ginger Gold 50', 'A-G03'=>'Ginger Gold 75'    
    );
    return $foods;
}

Ideally it would be databased so it wouldnt be so painful to write! it may be just as fast or quicker to write a mysql table with the columns
id,product_id,product_name,numberwithproduct
If you did that we could link up both functions to get their data from mysql and you just have to keep the mysql table up to date and everything on the site changes

After which ever you decide to do, put this in the listItems function right at the top:

 //CONFIG ARRAY
 $foods = getFoodArray();
 $foodsIdToName = getFoodKeyArray();

Then further down where it writes the html:

  $output[$type] .= "<tr><td>$foodsIdToName[$key]</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";

and that array will translate any product id to its name when ever you need it

I'll need to know a bit more about the taxes, will you be wanting to apply different tax amounts based on the location the user wants to ship to?

i'm about to leave work now but i can check later when i get home.

commented: Another good example of an Array +0
Member Avatar for LastMitch

@biiim,

I think I like your idea with to link up with the database for the food name. I think it will be a challenge but I want to try and see how that will work. Is this where I get the database for the food name:

$result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by items.itemName asc");
if (mysql_num_rows($result)==0){
echo mysql_num_rows($result);}
while($row = mysql_fetch_array($result)){
$_SESSION["mthis"] .=$row["itemName"]."\n" ;
$_SESSION["mthis"] .="itemNumber: ".$row["itemNumber"]."\n" ;
$_SESSION["mthis"] .="Qty: ".$row["qty"]."\n" ;
$_SESSION["mthis"] .="gift_wrap: ".ucwords($row["gift_wrap"])."\n" ;
$_SESSION["mthis"] .="Unit Price: ".$row["price"]."\n"."\n" ;
$sql="INSERT INTO order_details(o_id, prod_id, name, itemNumber, qty, gift_wrap, unitprice, total) VALUES (".
"'".mysql_real_escape_string($oid)."', ".
"'".mysql_real_escape_string($row["itemId"])."', ".
"'".mysql_real_escape_string($row["itemName"])."', ".
"'".mysql_real_escape_string($row["itemNumber"])."', ".
"'".mysql_real_escape_string($row["qty"])."', ".
"'".mysql_real_escape_string($row["gift_wrap"])."', ".
"'".mysql_real_escape_string($row["price"])."', ".
"'".mysql_real_escape_string($row["price"]*$row["qty"])."') ";
$rs= mysql_query($sql, $o_conn) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
}

About the taxes on my demo:

if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}}

This is the actually numbers for CT state:
Gifts containing candy, cookies, nuts, or any other items besides fruit & vegetables are subject to 6.35% sales tax.
As you can see and you're right about arrays get complicated! That's why I used fruits & vegetables I feel that is a simple way.
if the fruit is less than 50 than the tax is at .0 if it's more the tax rate .00635 For the vegatable it's at .00635.

6.35% sales tax if fruit & vegetables ($50) are sold within the state.

if($sstat == "CT"){
if($totalCost >= 50){
$taxx = round($totalCost * .00635,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .0,2);
}}

As you can see it does look similiar but I just make the cost lower for me to see the taxes demo work efficient.

As for the script you wrote it's really awesome. Matching Arrays are a pain but for certain things it does come in handle. But in the future, you're right it's much better using the method:

$Q = "SELECT product_id,product_cat,product_name,product_price FROM products";
$R = mysql_query($Q);
$foods = array();
while($prod = mysql_fetch_assoc($R)){
$foods[$prod['product_cat']]['items'] = array($prod['product_id'],$prod['product_price']);
}

I appreciate your insight again!

Like 'Ardav' said "All power to you!"

I'm not too sure what that means but if 'Ardav' said "All power to you!" it means you have more power than him

@Ardav

Is there someone else up there we can talk to?
No, now go away or I shall taunt you a second time!
Your mother was a hamster and your father smelled of elderberries!

I can smell that oder across the states. =)

Member Avatar for diafol

Runaway!!!!!!!!!

commented: I thought you love the smelled of elderberries +0
Member Avatar for LastMitch

@Biiim

You're right about the location. The Tax Exemption is connected to the shipping. I can't figure out the domestic & international shipping. When I click process it, the 'domestic shipping' change to 'international shipping' and it won't process.

Is there another word for $ship_country? At first it identifying the location. I think it's not identifying that word so that's the reason why when I click process it change the shipping cost.

I think I realized that in the 'functions.php' that you wrote

//3) Shipping
$domestic = array('United States');
if(in_array($ship_country,$domestic)){
//----------Domestic Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
if ($total_sales > 1000){$ship = 25.00;}
}else{
/----------International Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
if ($total_sales > 1000){$ship = 50.00;}
}

I also have to put this too:

if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}

I figure out how to isolate the state:

if ($sstat == "CT"){ $total_bill = $total_sales + $total_tax + $ship;}

Before then the shipping was on 1 page but now it's on the functions.php file and that everything has to go through that functions.php in order for the final process to go through.

This is what I wrote so far:

if ($sstat == "CT"){ $total_bill = $total_sales + $total_tax + $ship;}
$domestic = array('United States');
if(in_array($ship_country,$domestic)){
//----------Domestic Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
if ($total_sales > 1000){$ship = 25.00;}
}else{
/----------International Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
if ($total_sales > 1000){$ship = 50.00;}
}

So on the other page:

$cartdata = listItems($input,$_POST['country']);
$cartTotalCost = $cartdata['totalbill'];
$ship = $cartdata['shipping'];
$salesTotal = $cartdata['totalsales'];
$totalTax = $cartdata['totaltax'];
$ordertotal = $cartTotalCost + $express + $gift;

how do I merger this into the code above:

if ($sstat == "CT"){ $total_bill = $total_sales + $total_tax + $ship;}

so that it will realized that this state is exempted and will process.

For the Tax Exemption is working but I'm still figuring out how to make the "Item Name" appeared.

So I realized that these are the 2 issues I have. Once these 2 issues are resolve then the script works properly.

I mean when you separate the 1 file into 2 files to make things look more organized I think it's good idea. Its' always good to be organized. This is the first time I seen 1 file separate into 2 files and the function still works but not working properly. This is a new challenge.

I appreciate you taken your time to help me out and thanks insight again!

Member Avatar for LastMitch

@biiim

Here is the 2 files (I'm not too sure how to get it from the db). I kinda like the matching array I thought it was kinda cool. I'm always open for options kinda like seeing difference angles. The reason why certain things that 'Ardav' mention during these posts that I don't see those angles that's why it was very confusing to me understand his point of view. He didn't see my weakness. As your point of view, it's the same but a different level you can actually see my weakness is in arrays. I appreaciate that you taking your time to explained & teach me the correct way of how to write it and work on it ... hopefully I can get as good as you or better than 'Ardav'

Here is the 1st file:

<?
session_start();
header("Cache-control: private");
require_once ('include/init.php');

list($size, $price)=split($itemPriceSeparator, $_GET['id']);
//echo $price;
//error_reporting(E_ALL);

if (!is_numeric($price) && $price != "") {header('Location: shop.php');}

function GetCartId(){
    // This function will generate an encrypted string and
    // will set it as a cookie using set_cookie. This will
    // also be used as the cookieId field in the cart table

    if(isset($_COOKIE["cartId"])){
        return $_COOKIE["cartId"];
    }
    else{
    // There is no cookie set. We will set the cookie
    // and return the value of the users session ID

        setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
        return session_id();
    }
}

switch($_GET["action"]){
    case "add_item":{
        AddItem($_GET["id"], $_GET["qty"], $price);
        ShowCart();
        break;
    }
    case "update_item":{
        UpdateItem($_GET["id"], $_GET["qty"]);
        ShowCart();
        break;
    }
    case "empty_cart":{
        RemoveAll();
        ShowCart();
        break;
    }
    case "remove_item":{
        RemoveItem($_GET["id"]);
        ShowCart();
        break;
    }
    default: {
        ShowCart();
    }
}

function AddItem($itemId, $qty, $price){

    $itemId = mysql_real_escape_string($itemId);
    $qty    = mysql_real_escape_string($qty);
    $price  = mysql_real_escape_string($price);

    $result = mysql_query("select count(*) from cart where cookieId = '" . mysql_real_escape_string(GetCartId()) . "' and itemId = $itemId");

    $row = mysql_fetch_row($result);
    $numRows = $row[0];

    if($numRows == 0){
        $sql = "insert into cart(cookieId, itemId, qty, price) values(
                '" . mysql_real_escape_string(GetCartId()) . "', $itemId, $qty, $price)";
        mysql_query($sql);
        echo mysql_error();
    }
    else{
        UpdateItemThere($itemId, $qty);
    }
}

function UpdateItem($itemId, $qty){

    $itemId = mysql_real_escape_string($itemId);
    $qty    = mysql_real_escape_string($qty);

    mysql_query("update cart set qty = $qty where cookieId = '" . mysql_real_escape_string(GetCartId()) . "' and cartId = $itemId");
}

function UpdateItemThere($itemId, $qty){

    $itemId = mysql_real_escape_string($itemId);
    $qty    = mysql_real_escape_string($qty);

    $query3     = "SELECT qty FROM cart where cookieId = '" . mysql_real_escape_string(GetCartId()) . "' and itemId = $itemId";
    $result3    = mysql_query($query3);
    $row3       = mysql_fetch_array($result3);
    $newqty     = $row3["qty"] + $qty;

    $newqty     = mysql_real_escape_string($newqty);

    mysql_query("update cart set qty = ". $newqty." WHERE cookieId = '" . mysql_real_escape_string(GetCartId()) . "' and itemId = $itemId'");
}

function RemoveItem($itemId){

    $itemId = mysql_real_escape_string($itemId);

    mysql_query("delete from cart where cookieId = '" . mysql_real_escape_string(GetCartId()) . "' and cartId = $itemId"); 
}

function RemoveAll(){
    mysql_query("delete from cart where cookieId = '" . mysql_real_escape_string(GetCartId()) . "'"); 
}

function ShowCart( ){ 

    $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . mysql_real_escape_string( GetCartId() ) . "' order by cart.cartId DESC");

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="style.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
.style1 {font-family: Helvetica, sans-serif; font-size: 9pt; color: #FFFFFF;}
.style2 {font-weight: bold}
-->
</style>
</head>
    <body>
            <?php include("header.php");?>
                <table width="640" style="position:relative; top:-50px;" align="center" cellpadding="0" cellspacing="0">
                 <tr>
                  <td valign="top"><table width="98%" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC">
                      <tr>
                        <td height="101" valign="top" bgcolor="#FFFFFF" class="navtitle"><div align="center">SHOPPING CART <br>  
                            <br>
                        </div>
                          <table width="100%" align="center" cellpadding="2" cellspacing="1" class="navtitle">
                  <tr>
                    <td width="18%" bgcolor="#CCCCCC" class="navtitle"><span class="style1">ITEM NUMBER</span></td>
                    <td width="54%" height="20" bgcolor="#CCCCCC"><span class="style1">ITEM</span></td>
                    <td height="20" bgcolor="#CCCCCC" class="navtitle"><span class="style1">QTY</span></td>
                    <td height="20" bgcolor="#CCCCCC" class="style1 navtitle"><span class="style1">COST </span></td>
                    <td height="20" bgcolor="#CCCCCC" class="style1 navtitle" width="6%"></td>
                  </tr>
                  <? 
    if (mysql_num_rows($result)==0)
    {
        $aa = mysql_num_rows($result);
    }

$totalCost = "";
while($row = mysql_fetch_array($result))
{
// Increment the total cost of all items
$totalCost += ($row["qty"] * $row["price"]);
$a = 1;
?>
                  <tr>
                    <td height="25"><?php echo $row["itemNumber"]; ?></td>
                    <td><?php echo $row["itemName"]; ?></td>
                    <td width="10%">
                      <select name="<?php echo $row["cartId"]; ?>" onChange="UpdateQty(this)">
                        <option selected="selected">
                          <?=$row["qty"];?>
                        </option>
                        <?
    for($i = 1; $i <= 100; $i++)
    {
    echo "<option>" . $i . "</option>";
    }
    ?>
                    </select>                    
               </td>
               <td width="9%" height="20" >$ <?php echo number_format($row["price"] * $row["qty"], 2, ".", ","); ?></td>
               <td width="11%" height="20"><a href="cart.php?action=remove_item&id=<?php echo $row["cartId"]; ?>">Remove</a></td>
           </tr>
           <?php
}

// Increment the total cost of all items
$totalCost += ($row["qty"] * $row["price"]);

$totalCost = $totalCost + ($row["qty"] * $row["price"]);
?>
                      <script language="JavaScript" type="text/javascript">

                            var tempItem    = null;
                            var tempCartId  = null;

                            function UpdateQty(item){
                                itemId = item.name;
                                newQty = item.options[item.selectedIndex].text;
                                document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;
                            }
                    </script>
                  <tr>
                    <td colspan="5"><hr size="1" NOSHADE color="gray" class="style2"></td>
                  </tr>
                  <tr>
                    <td colspan="2"class="navtitlesm"><a href="index.php">BACK TO SHOPPiNG </a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="cart.php?action=empty_cart&amp;id=<?php echo $row["itemId"]; ?>">EMPTY CART</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="checkout.php">CHECKOUT</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <td colspan="2"><b>&nbsp;&nbsp;&nbsp;&nbsp;TOTAL&nbsp;:&nbsp$ <?php echo number_format($totalCost, 2, ".", ","); ?></b></td>
                  </tr>
                  <? } ?>
                          </table>
                        <br>
                        <br></td>
                      </tr>
                  </table>                               </td>
                  </tr>
                 <tr>
                   <td height="300" valign="top" bgcolor="#FFFFFF" class="navtitle" style=" padding-top:10px"><table width="600" border="0" align="center" cellpadding="4" cellspacing="0" style="border:1px solid  #999999;">
                   </table>
                     <br>
                     <table width="86%" border="0" align="center" cellpadding="0" cellspacing="0">
                     <tr>
                       <td class="navlight"><? include("include/menu.php"); ?></td>
                     </tr>
                   </table></td>
                  </tr>
    </table>
                              <p>&nbsp;</p>
                              <? include("footer.php");?>                
                              <p>&nbsp;</p>
</body>
</html>

Here is the 2nd file:

<?php
session_start();
//fix for ie back button 
header("Cache-control: private");
include("include/init.php");

list($price1) = split($itemPriceSeparator, $_GET['itemNumber1']);
list($price2) = split($itemPriceSeparator, $_GET['itemNumber2']);
list($price3) = split($itemPriceSeparator, $_GET['itemNumber3']);
list($price4) = split($itemPriceSeparator, $_GET['itemNumber4']);
list($price5) = split($itemPriceSeparator, $_GET['itemNumber5']);

//debug...
//die($price1 . ' / ' . $price2 . ' / ' . $price3 . ' / ' . $price4 . ' / ' . $price5);

if (!is_numeric($price) && $price != "") {header('Location: catalog.php');}

    function GetCartId(){
        // This function will generate an encrypted string and
        // will set it as a cookie using set_cookie. This will
        // also be used as the cookieId field in the cart table

        if(isset($_COOKIE["cartId"])){
            return $_COOKIE["cartId"];
        }
        else{
        // There is no cookie set. We will set the cookie
        // and return the value of the users session ID

            setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
            return session_id();
        }
    }

switch($_GET["action"])
{
case "add_multiple":
{
    if ($_GET['item_5'] != "selected"){$_GET["id5"] = "";}
    if ($_GET['item_4'] != "selected"){$_GET["id4"] = "";}
    if ($_GET['item_3'] != "selected"){$_GET["id3"] = "";}
    if ($_GET['item_2'] != "selected"){$_GET["id2"] = "";}
    if ($_GET['item_1'] != "selected"){$_GET["id1"] = "";}

AddMultiple(
    $_GET["id1"], $_GET["id2"], $_GET["id3"], $_GET["id4"], $_GET["id5"], 
     $_GET["itemNumber"], $price1, 
     $_GET["itemNumber"], $price2, 
     $_GET["itemNumber"], $price3, 
     $_GET["itemNumber"], $price4, 
     $_GET["itemNumber"], $price5
);
    header("Location:cart.php");//redirect user to cart.php

}break;

case "add_item":
{
AddItem($_GET["id"], $_GET["qty"], $price);
ShowCart();
break;
}
case "update_item":
{
UpdateItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "empty_cart":
{
RemoveAll();
ShowCart();
break;
}
case "remove_item":
{
RemoveItem($_GET["id"]);
ShowCart();
break;
}
default:
{
ShowCart();
}
}

function AddItem($itemId, $qty, $itemNumber, $price){

$result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

$row = mysql_fetch_row($result);
$numRows = $row[0];

if($numRows == 0)
{
mysql_query("insert into cart(cookieId, itemId, qty, itemNumber, price) values('" . GetCartId() . "', $itemId, $qty, '$itemNumber', $price)");
echo mysql_error();
}
else
{
UpdateItemThere($itemId, $qty);
}
}

function AddMultiple($itemId1, $itemId2, $itemId3, $itemId4, $itemId5, $itemNumber1, $price1, $itemNumber2, $price2, $itemNumber3, $price3, $itemNumber4, $price4, $itemNumber5, $price5){
    $cart_id = GetCartId();
    $cart_id = mysql_real_escape_string($cart_id);

    //escape strings for inserting into db-------//
    $itemId1 = mysql_real_escape_string($itemId1);
    $itemId2 = mysql_real_escape_string($itemId2);
    $itemId3 = mysql_real_escape_string($itemId3);
    $itemId4 = mysql_real_escape_string($itemId4);
    $itemId5 = mysql_real_escape_string($itemId5);

    $itemNumber1 = mysql_real_escape_string($itemNumber1);
    $itemNumber2 = mysql_real_escape_string($itemNumber2);
    $itemNumber3 = mysql_real_escape_string($itemNumber3);
    $itemNumber4 = mysql_real_escape_string($itemNumber4);
    $itemNumber5 = mysql_real_escape_string($itemNumber5);

    $price1 = mysql_real_escape_string($price1);
    $price2 = mysql_real_escape_string($price2);
    $price3 = mysql_real_escape_string($price3);
    $price4 = mysql_real_escape_string($price4);
    $price5 = mysql_real_escape_string($price5);
    //escape strings for inserting into db-------//

    mysql_query("insert into cart(cookieId, itemId, qty, itemNumber, price) values('" . $cart_id. "',  $itemId1, 1, '$itemNumber1', $price1)");

    mysql_query("insert into cart(cookieId, itemId, qty, itemNumber, price) values('" . $cart_id . "', $itemId2, 1, '$itemNumber2', $price2)");

    mysql_query("insert into cart(cookieId, itemId, qty, itemNumber, price) values('" . $cart_id . "', $itemId3, 1, '$itemNumber3', $price3)");

    mysql_query("insert into cart(cookieId, itemId, qty, itemNumber, price) values('" . $cart_id . "', $itemId4, 1, '$itemNumber4', $price4)");

    mysql_query("insert into cart(cookieId, itemId, qty, itemNumber, price) values('" . $cart_id . "', $itemId5, 1, '$itemNumber5', $price5)");
}


function UpdateItem($itemId, $qty)

{
    mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and cartId = $itemId");
}

function UpdateItemThere($itemId, $qty)

{
$query3= "SELECT qty FROM cart where cookieId = '" . GetCartId() . "' and itemId = $itemId";
$result3 = mysql_query($query3);
$row3 = mysql_fetch_array($result3);
$newqty = $row3["qty"] + $qty;
    mysql_query("update cart set qty = ". $newqty." WHERE cookieId = '" . GetCartId() . "' and itemId = $itemId");
}

function RemoveItem($itemId){
    mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and cartId = $itemId"); 
}

function RemoveAll(){
    mysql_query("delete from cart"); 
}

function ShowCart( )
{ 

$result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName asc");

 ?>

<!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></title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
<!--
.style4 {color: #333; font-size: 12px; font-family:Georgia, "Times New Roman", Times, serif}
.style7 {font-size: 10px;font-weight: bold;}
.style8 {color: #333; font-size: 10px; font-family: Georgia, "Times New Roman", Times, serif; font-weight: bold; }
-->
</style>
</head>
<body>
<div align="center">
    <? include("header.php");?>
<table width="640" border="0" style="position:relative; top:-50px;" align="center" cellpadding="8" bordercolor="0">
    <tr>
        <td width="21%" align="left" valign="top">
            <table border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC">
                <tr>
                    <td height="300" valign="top" bgcolor="#FFFFFF"  class="navtitle" style=" padding-top:46px">
                        <? include("include/menu.php"); ?>
                    </td>
                 </tr>
            </table> 
        </td>
        <td width="78%">
        <table align="center" cellspacing="2">
        <tr>
            <td height="101" valign="top" bgcolor="#FFFFFF" class="navtitle" colspan="6">
                <div align="center">
                    SHOPPING CART <br/><br/>
                </div>
            </td>
        </tr>
         <tr>
          <td width="18%" bgcolor="#CCCCCC" class="navtitle"><span class="style1 style7"><strong>ITEM NUMBER</strong></span></td>
          <td width="54%" height="20" bgcolor="#CCCCCC"><span class="style1 style7"><strong>ITEM</strong></span></td>
          <td height="20" bgcolor="#CCCCCC" class="navtitle"><span class="style1 style7"><strong>QTY</strong></span></td>
          <td height="20" bgcolor="#CCCCCC" class="style1 navtitle"><strong>COST </span></strong></td>
          <td height="20" bgcolor="#CCCCCC" class="style1 navtitle" width="6%"></td>
        <td height="25" align="center" bgcolor="#CCCCCC" class="style1 navtitle"></td>
  </tr>
<? 

    if (mysql_num_rows($result)==0)
    {
        echo mysql_num_rows($result);
    }

while($row = mysql_fetch_array($result))
{
// Increment the total cost of all items
$totalCost += ($row["qty"] * $row["price"]);
$a = 1;
?>

<tr>
<td height="25"><span class="style2"><font face="verdana" size="1"><?php echo $row["color"]; ?></font></span></td>
<td><span class="style2"><font face="verdana" size="1"><?php echo $row["itemName"]; ?> - coordinate</font></span></td>
<td><span class="style2"><font face="verdana" size="1"> <?php echo $row["size"]; ?></font></span></td>
<td width="7%"><span class="style2"><font face="verdana" size="1">
    <select name="<?php echo $row["cartId"]; ?>" onChange="UpdateQty(this)">
  <option selected="selected"><?=$row["qty"];?></option>
    <?
    for($i = 1; $i <= 100; $i++)
    {
    echo "<option>" . $i . "</option>";
    }
    ?>
  </select>
</font></span></td>
<td width="10%" height="25">
  <span class="style2"><font face="verdana" size="1">
$<?php echo number_format($row["price"]*$row["qty"], 2, ".", ","); ?></font></span></td>
<td width="7%" height="25">
  <span class="style2">
  <a href="cart.php?action=remove_item&id=<?php echo $row["cartId"]; ?>"><font face="verdana" size="1">Remove</font></a></span></td>
</tr>
<?php
}

// Increment the total cost of all items
$totalCost += ($row["qty"] * $row["price"]);
$totalCost = $totalCost + ($row["qty"] * $row["price"]);
?> 

<script language="JavaScript">

function UpdateQty(item)
{
itemId = item.name;
newQty = item.options[item.selectedIndex].text;
document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;
}

</script>

<tr>
<td colspan="6">
<hr size="1" NOSHADE color="gray" class="style2"></td>
</tr>
<tr>
<td colspan="4">
  <span class="style2">
  <a href="index.php"><font face="verdana" size="1">&lt;&lt; Keep Shopping</font></a></span>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <span class="style2"><a href="cart.php?action=empty_cart&amp;id=<?php echo $row["itemId"]; ?>"><font face="verdana" size="1">Empty Cart</font></a></span>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="checkout.php"><font face="verdana" size="1">Checkout</font></a>
    <div align="center" class="style2"></div></td>
<td colspan="2">
  <span class="style8">
  <b>TOTAL: $<?php echo number_format($totalCost, 2, ".", ","); ?></b></span></td>
</tr>
<? } ?>
</table></td></tr>
</table>
<p>&nbsp;</p>
<? include("footer.php");?>
</div>
</body>
</html>

phew thats alot of code, i think its not much use for the tax but it shows me a bit about your database in the mysql queries.

looking at the functions these ones could be wrong?

function UpdateItem($itemId, $qty)
{
mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and cartId = $itemId");
}

The add item function & query in that refers to an item in the database as itemId not cartId

function UpdateItem($itemId, $qty)
{
    mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");
}

function RemoveItem($itemId){
mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and cartId = $itemId");
}

Same again

function RemoveItem($itemId){
    mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId"); 
}

function RemoveAll(){
mysql_query("delete from cart");
}

This sounds like it will delete everyones cart

function RemoveAll(){
    mysql_query("delete from cart WHERE cookieId = '".GetCartId()."'"); 
}

Do you have a product page on your site that pulls product data out? or where does this itemId come from you may already have a product table set up

The tax wont be too hard to set if if you don't have many variations

$cartdata = listItems($input,$_POST['country']);

that line passes $_POST['country'] into the function and assigns it as $ship_country

instead you could call listItems($input,$sstat);

then just change the function to tell it what you want to happen when it equals "CT"

$domestic = array('United States');
if($ship_country == "CT"){
$ship = 6.00;
}elseif($ship_country == "United States"){
//----------Domestic Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
if ($total_sales > 1000){$ship = 25.00;}
}else{
/----------International Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
if ($total_sales > 1000){$ship = 50.00;}
}

The tax would be a little more complex, as it is setup you need to pass the $ship_country variable into the getFoodArray() function

 //CONFIG ARRAY
    $foods = getFoodArray($ship_country);

This is a little messy but then change the function like this:

function getFoodArray($ship_country){
    if($ship_country == "CT"){
        $foods = array(
        "fruit"=> array("items"=>array(
        //Fruit--------------------
        //Apple----------
        //Cortland
        'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
        //Ginger Gold 
        'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75, 
        //Idared
        'A-I01'=>35, 'A-I02'=>50, 'A-I03'=>75, 
        //McIntosh
        'A-M01'=>35, 'A-M02'=>50, 'A-M03'=>75, 
        //Grapefruit
        'G-001'=>35, 'G-002'=>50, 'G-003'=>75,
        //Lemon
        'L-001'=>35, 'L-002'=>50, 'L-003'=>75,
        //Orange
        'O-001'=>35, 'O-002'=>50, 'O-003'=>75,  
        //Pears 
        'P-001'=>35, 'P-002'=>50, 'P-003'=>75, 
        //Tangerine
        'T-001'=>35, 'T-002'=>50, 'T-003'=>75,   
        //Asian Pears 
        'P-A01'=>55, 'P-A02'=>105, 'P-A03'=>165, 
        //Guava
        'G-V01'=>55, 'G-V02'=>105, 'G-V03'=>165,  
        //Kiwi
        'K-001'=>55, 'K-002'=>105, 'K-003'=>165,  
        //Mango
        'M-001'=>55, 'M-002'=>105, 'M-003'=>165,  
        //Papaya
        'P-P01'=>55, 'P-P02'=>105, 'P-P03'=>165, 
        //Pomegranate
        'P-001'=>55, 'P-002'=>105, 'P-003'=>165,   
        //Star fruit
        'S-001'=>55, 'S-002'=>105, 'S-003'=>165,    
        //Cantaloupe
        'C-001'=>55, 'C-002'=>95, 'C-003'=>120, 
        //Honey Dew
        'H-001'=>55, 'H-002'=>95, 'H-003'=>120, 
        //Watermelon
        'W-001'=>55, 'W-002'=>95, 'W-003'=>120, 
        //Banana
        'B-001'=>35, 'B-002'=>50, 'B-003'=>75, 
        //Lychee
        'L-Y01'=>55, 'L-Y02'=>105, 'L-Y03'=>165,
        //Cranberry 
        'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
        //Raspberry
        'R-B01'=>20, 'R-B02'=>30, 'R-B03'=>50, 
        //Cherry ---------
        //Black 
        'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
        //Chelan
        'C-C01'=>20, 'C-C02'=>30, 'C-C03'=>50, 
        //Sweet Cherry
        'C-S01'=>20, 'C-S02'=>30, 'C-S03'=>50, 
        //Grapes----------
        //Purple
        'G-P01'=>20, 'G-P02'=>30, 'G-P03'=>50, 
        //Red
        'G-R01'=>20, 'G-R02'=>30, 'G-R03'=>50, 
        //White
        'G-W01'=>20, 'G-W02'=>30, 'G-W03'=>50, 
        ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.875),
        "vegetable"=> array("items"=>array(
        //Vegetable--------------------
        //Asparagus
        'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80, 
        //Broccoli
        'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80, 
        //Carrots
        'C-A01'=>35, 'C-C02'=>55, 'C-C03'=>80, 
        //Celery
        'C-E01'=>35, 'C-E02'=>55, 'C-E03'=>80, 
        //Cucumber
        'C-U01'=>35, 'C-U02'=>55, 'C-U03'=>80,  
        //Eggplant
        'E-P01'=>35, 'E-P02'=>55, 'E-P03'=>80, 
        //Garlic
        'G-L01'=>35, 'G-L02'=>55, 'G-L03'=>80, 
        //Ginger
        'G-G01'=>35, 'G-G02'=>55, 'G-G03'=>80, 
        //Green Bean
        'G-B01'=>35, 'G-B02'=>55, 'G-B03'=>80, 
        //Iceberg Lettuce 
        'I-L01'=>35, 'I-L02'=>55, 'I-L03'=>80, 
        //Lettuce 
        'L-T01'=>35, 'L-T02'=>55, 'L-T03'=>80, 
        //Tomoto
        'T-O01'=>35, 'T-O02'=>55, 'T-O03'=>80, 
        //Potato
        'P-O01'=>35, 'P-O02'=>55, 'P-O03'=>80, 
        //Onion
        'O-N01'=>35, 'O-N02'=>55, 'O-N03'=>80, 
        //Snow pea 
        'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
        //Soybean 
        'S-B01'=>35, 'S-B02'=>55, 'S-B03'=>80,  
        //Spinach
        'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
        //Squash
        'S-Q01'=>35, 'S-Q02'=>55, 'S-Q03'=>80, 
        //Sweet Corn
        'S-C01'=>35, 'S-C02'=>55, 'S-C03'=>80,   
        //Sweet Potato
        'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80,    
        //Chinese Long Beans
        'CH-LB01'=>45, 'CH-LB02'=>90, 'CH-LB03'=>175, 
        //Chinese Kai-lan
        'CH-KL01'=>45, 'CH-KL02'=>90, 'CH-KL03'=>175, 
        //Chinese Pak choy
        'CH-PC01'=>45, 'CH-PC02'=>90, 'CH-PC03'=>175, 
        //Chinese Taro
        'CH-TA01'=>45, 'CH-TA02'=>90, 'CH-TA03'=>175, 
        //Chinese Water Chestnut
        'CH-WC01'=>45, 'CH-WC02'=>90, 'CH-WC03'=>175, 
        //Chinese Winter melon
        'CH-WM01'=>45, 'CH-WM02'=>90, 'CH-WM03'=>175, 
        ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.875));
    }else{
        $foods = array(
        "fruit"=> array("items"=>array(
        //Fruit--------------------
        //Apple----------
        //Cortland
        'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
        //Ginger Gold 
        'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75, 
        //Idared
        'A-I01'=>35, 'A-I02'=>50, 'A-I03'=>75, 
        //McIntosh
        'A-M01'=>35, 'A-M02'=>50, 'A-M03'=>75, 
        //Grapefruit
        'G-001'=>35, 'G-002'=>50, 'G-003'=>75,
        //Lemon
        'L-001'=>35, 'L-002'=>50, 'L-003'=>75,
        //Orange
        'O-001'=>35, 'O-002'=>50, 'O-003'=>75,  
        //Pears 
        'P-001'=>35, 'P-002'=>50, 'P-003'=>75, 
        //Tangerine
        'T-001'=>35, 'T-002'=>50, 'T-003'=>75,   
        //Asian Pears 
        'P-A01'=>55, 'P-A02'=>105, 'P-A03'=>165, 
        //Guava
        'G-V01'=>55, 'G-V02'=>105, 'G-V03'=>165,  
        //Kiwi
        'K-001'=>55, 'K-002'=>105, 'K-003'=>165,  
        //Mango
        'M-001'=>55, 'M-002'=>105, 'M-003'=>165,  
        //Papaya
        'P-P01'=>55, 'P-P02'=>105, 'P-P03'=>165, 
        //Pomegranate
        'P-001'=>55, 'P-002'=>105, 'P-003'=>165,   
        //Star fruit
        'S-001'=>55, 'S-002'=>105, 'S-003'=>165,    
        //Cantaloupe
        'C-001'=>55, 'C-002'=>95, 'C-003'=>120, 
        //Honey Dew
        'H-001'=>55, 'H-002'=>95, 'H-003'=>120, 
        //Watermelon
        'W-001'=>55, 'W-002'=>95, 'W-003'=>120, 
        //Banana
        'B-001'=>35, 'B-002'=>50, 'B-003'=>75, 
        //Lychee
        'L-Y01'=>55, 'L-Y02'=>105, 'L-Y03'=>165,
        //Cranberry 
        'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
        //Raspberry
        'R-B01'=>20, 'R-B02'=>30, 'R-B03'=>50, 
        //Cherry ---------
        //Black 
        'C-B01'=>20, 'C-B02'=>30, 'C-B03'=>50, 
        //Chelan
        'C-C01'=>20, 'C-C02'=>30, 'C-C03'=>50, 
        //Sweet Cherry
        'C-S01'=>20, 'C-S02'=>30, 'C-S03'=>50, 
        //Grapes----------
        //Purple
        'G-P01'=>20, 'G-P02'=>30, 'G-P03'=>50, 
        //Red
        'G-R01'=>20, 'G-R02'=>30, 'G-R03'=>50, 
        //White
        'G-W01'=>20, 'G-W02'=>30, 'G-W03'=>50, 
        ),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),
        "vegetable"=> array("items"=>array(
        //Vegetable--------------------
        //Asparagus
        'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80, 
        //Broccoli
        'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80, 
        //Carrots
        'C-A01'=>35, 'C-C02'=>55, 'C-C03'=>80, 
        //Celery
        'C-E01'=>35, 'C-E02'=>55, 'C-E03'=>80, 
        //Cucumber
        'C-U01'=>35, 'C-U02'=>55, 'C-U03'=>80,  
        //Eggplant
        'E-P01'=>35, 'E-P02'=>55, 'E-P03'=>80, 
        //Garlic
        'G-L01'=>35, 'G-L02'=>55, 'G-L03'=>80, 
        //Ginger
        'G-G01'=>35, 'G-G02'=>55, 'G-G03'=>80, 
        //Green Bean
        'G-B01'=>35, 'G-B02'=>55, 'G-B03'=>80, 
        //Iceberg Lettuce 
        'I-L01'=>35, 'I-L02'=>55, 'I-L03'=>80, 
        //Lettuce 
        'L-T01'=>35, 'L-T02'=>55, 'L-T03'=>80, 
        //Tomoto
        'T-O01'=>35, 'T-O02'=>55, 'T-O03'=>80, 
        //Potato
        'P-O01'=>35, 'P-O02'=>55, 'P-O03'=>80, 
        //Onion
        'O-N01'=>35, 'O-N02'=>55, 'O-N03'=>80, 
        //Snow pea 
        'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
        //Soybean 
        'S-B01'=>35, 'S-B02'=>55, 'S-B03'=>80,  
        //Spinach
        'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80, 
        //Squash
        'S-Q01'=>35, 'S-Q02'=>55, 'S-Q03'=>80, 
        //Sweet Corn
        'S-C01'=>35, 'S-C02'=>55, 'S-C03'=>80,   
        //Sweet Potato
        'S-P01'=>35, 'S-P02'=>55, 'S-P03'=>80,    
        //Chinese Long Beans
        'CH-LB01'=>45, 'CH-LB02'=>90, 'CH-LB03'=>175, 
        //Chinese Kai-lan
        'CH-KL01'=>45, 'CH-KL02'=>90, 'CH-KL03'=>175, 
        //Chinese Pak choy
        'CH-PC01'=>45, 'CH-PC02'=>90, 'CH-PC03'=>175, 
        //Chinese Taro
        'CH-TA01'=>45, 'CH-TA02'=>90, 'CH-TA03'=>175, 
        //Chinese Water Chestnut
        'CH-WC01'=>45, 'CH-WC02'=>90, 'CH-WC03'=>175, 
        //Chinese Winter melon
        'CH-WM01'=>45, 'CH-WM02'=>90, 'CH-WM03'=>175, 
        ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75));
    }
    return $foods;
}

you could actually use the array to create the table of products but you may want to be more familiar with mysql before you start using it to store your products.

A good program i use to manage mysql is sqlyog it has a free version, somewhere in your site probably a config.php file or configure.php it should define how your website connects to mysql.

require_once ('include/init.php');

it might be in that file for you. There will be a host, username and password you can use that in sqlyog to connect to the database and you will be able to see all the tables & data stored for your website.

to put your data in a table i put this together:

    $Q = "CREATE TABLE `aproducts`(     `id` INT(7) NOT NULL AUTO_INCREMENT ,     `itemId` VARCHAR(10) ,     `category` VARCHAR(20) ,     `value` INT(3) ,     PRIMARY KEY (`id`)  );";
    mysql_query($Q) or die(mysql_error());
    $Q = "ALTER TABLE `aproducts` ADD UNIQUE `itemid` (`itemId`)";
    mysql_query($Q);
    foreach($foods['fruit']['items'] as $k=>$v){
        $Q = "INSERT IGNORE INTO `aproducts` (`itemid`,`category`,`value`) VALUES('{$k}','fruit',{$v})";
        echo $Q."<br/>\r\n";
        mysql_query($Q);
    }
    foreach($foods['vegetable']['items'] as $k=>$v){
        $Q = "INSERT IGNORE INTO `aproducts` (`itemid`,`category`,`value`) VALUES('{$k}','vegetable',{$v})";
        echo $Q."<br/>\r\n";
        mysql_query($Q);
    }

run that on a page once and you should have a products table

Member Avatar for LastMitch

Hi Biiim,

You're right about the

mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");

I pasted the wrong file which is the same but always used those two files that I posted above as a reference

It's getting really complex. I think I will take a few steps back to try to grasp what you wrote. I thought I was getting close to resolve the issue but now it's like a paradox box. I'm still having the issue with the tax & shipping. For the taxes it only applies to 1 state which is "CT" and the other 49 states is exempted. The issue is that still tax other states and the shipping is not working correctly

This is what I wrote base on your code:

  $domestic = array('United States');
  if($ship_country == "CT"){
  if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
  if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
  if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
  if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
  if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
  if ($total_sales > 1000){$ship = 25.00;}
  }elseif(in_array($ship_country,$domestic)){
  //----------Domestic Shipping--------------//
  if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
  if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
  if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
  if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
  if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
  if ($total_sales > 1000){$ship = 25.00;}
  }else{
  //----------International Shipping--------------//
  if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
  if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
  if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
  if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
  if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
  if ($total_sales > 1000){$ship = 50.00;}
  }

Here is the CONFIG

  function listItems($input,$ship_country,$sstat){
  //CONFIG ARRAY
  $foods = getFoodArray($ship_country);

For the taxes I shorten so you can explained what I did wrong:

To isolate the sale tax for just "CT" state which was my old one is

  if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}

But now you help me create a new code which I'm not familiar with but I'm trying to understand it.

  function getFoodArray($ship_country){
  if($ship_country == "CT"){
  $foods = array(
  "fruit"=> array("items"=>array(

  //Fruit--------------------
  //Apple
  //Cortland
  'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
  //Ginger Gold
  'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75,
  ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.875),

  "vegetable"=> array("items"=>array(
  //Vegetable--------------------
  //Asparagus
  'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80,
  //Broccoli
  'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80,
  ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.875));

  }else{

  $foods = array(
  "fruit"=> array("items"=>array(
  //Fruit--------------------
  //Apple
  //Cortland
  'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
  //Ginger Gold
  'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75,
  ),"tax_ex_limit"=> 30, "tax_ex_rate"=>4.5, "tax_rate"=>8.75),

  "vegetable"=> array("items"=>array(
  //Vegetable--------------------
  //Asparagus
  'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80,
  //Broccoli
  'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80,
  ),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>8.75));
  }
  return $foods;
  }

I'm getting the same issue yesterday when I click on the Submit button to submit checkout sheet to PayPal it won't goes through and it also at the same time it changes the shipping price from the 'domestic shipping' to 'international shipping' . I follow all the instruction and modify your code into my code and it still won't work.

Here is the other code:

  if (mysql_num_rows($result)==0){
   echo mysql_num_rows($result);
      }
      $_SESSION["mthis"] ="";
   $input = array();
  while($row = mysql_fetch_array($result)){
  //loop through all items in the current cart?
  //$row['itemId'] should match up to the codes in the $foods array
  $input[] = array($row['itemId'],$row['qty']);
  //$input[] = array($row['itemId'],5);//test it with just a quantity of 5 for each item
   }
   $cartdata = listItems($input,$ship_country,$sstat);
   $cartTotalCost = $cartdata['totalbill'];
  $ship = $cartdata['shipping'];
  $salesTotal = $cartdata['totalsales'];
  $totalTax = $cartdata['totaltax'];
  $ordertotal = $cartTotalCost + $express + $gift;
   //--------store important values in session--------------//
  $_SESSION['tcost'] = $totalCost;
  $_SESSION['ship'] = $ship;
  $_SESSION['taxx'] = $totalTax;
   //----------store important values in session--------------//
   echo $cartdata['html']

Do I need to re-configure the info above in order to submit it to the payment process?

For the item name, I still trying to figure it out how to put

  $row['itemName'] into the $input[ ]
  $input[ ] = array($row['itemId'],$row['qty']);

Is there another way to make the 'itemName' to appear on the sheet in the input? I try to put it on the checkout sheet:

  echo $row['itemName'];
  $input[ ] = array($row['itemId'],$row['qty']);

and it did appear on top of the itemName (I'm using the dashes to line it up it's doesn't have dashes on the table)

  ------------     Broccoli
  ItemID  *  ItemName  *  Qty   * Cost
  B-B01    --------------------3----$105

Do you have any suggest?

I'm closing to getting it done.

The taxes & shipping and the ItemName and the submit form is the 3 last issues.

I appreciated that you taking your time to help me out!

I appreciate your insight again!

I wish I could help, but Biim already got it under control, and doing a hell of an excellent job .. :) At the least, I managed to provide my humble contribution of a short definition of vegetables and fruits... :)

You can also put your important values in session as an array.. for example,

  $_SESSION['important'] = array($data1, $datat2, $data3,$data4, $moreHereIfyouWant);

Then you can easily access session items from the array by

   $_SESSION['important'][0]; // for data1
   $_SESSION['important'][1]; // for data2
   ## add as many as you want.

Not much of a contribution from me, but I hope it can be considered..

Honestly, it is looking pretty good guys...

It's getting really complex. I think I will take a few steps back to try to grasp what you wrote.

haha i was thinking that too, i think just concentrate on whats not working and get the thing working however messy the code is

I thought I was getting close to resolve the issue but now it's like a paradox box. I'm still having the issue with the tax & shipping. For the taxes it only applies to 1 state which is "CT" and the other 49 states is exempted. The issue is that still tax other states and the shipping is not working correctly

so for 49 states, there is a rate of 4.5% tax on fruit under the value of $30 and 8.75% tax over $30?

and for the other state "CT" it has a fixed tax rate on fruit of 8.75%?

i dont quite get what the tax needs to be is why i'm not sure what to write

I'm getting the same issue yesterday when I click on the Submit button to submit checkout sheet to PayPal it won't goes through and it also at the same time it changes the shipping price from the 'domestic shipping' to 'international shipping' . I follow all the instruction and modify your code into my code and it still won't work.

wheres the paypal form code? i dont think paypal has any private merchant codes but take any out incase

Is there another way to make the 'itemName' to appear on the sheet in the input? I try to put it on the checkout sheet:

I need to know where your product data is stored, where is a page that adds something to the cart? one that calls this bit by the sounds of it AddItem($itemId, $qty, $price) need to know where that page got the product details from ie. $itemId, $price. Hopefully it is getting it from a product database so i can just write it into an array and you dont need to type all the names in that would be rather painful!

@veedeoo

haha i like your new picture, that is true shopping carts are easier to put into sessions but id hate trying to get all that rewritten when its already working(i hope) in mysql

commented: The example was a overwhelming but it's good that you know +0
Member Avatar for LastMitch

Hi Biiim,

Let's Regroup. I apologizes I think I haven't explained it clear. I really appreciated take some time to teach me how to understand the arrays and I also realized "tax exemption" is an awful and painful to write and create. The reason there is too many different taxes.

1st Issue. The tax exemption.

It applies for 1 state (1 Crown Colony) which is "CT"

The matching array script is awesome! It matches the items and it make tax exemption works.

I just want 1 state (1 Crown Colony) to have the taxes & tax exemption which is "CT"

The other 49 states (49 Crown Colonies) doesn't apply.

and the international countries doesn't apply either.

For functions.php file which you create and separate is great!

This is my old sales tax I created:

if ($sstat == "CT"){$taxx = round($totalCost * .08875,2);}

The one I wrote above means that state "CT" has a sale tax. It means (Total Cost (all of the items) * .08875)

The new one that I wanted to learn to create but I didn't know how which you created for me (this is a demo one which I want to see how it looks like and write it correctly):

if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}}

This means that if the

"Total Cost is greater than $30" then the sale tax is .08875"

elseif

"Total Cost is greater than 0" then the sale tax is .00475"

I need to separate the fruits & vegetables items which you teach me to how to create the arrays and you help me with the tax exemption in the function.php.

Since you created that tax exemption in the function.php file. I don't need the one:

if($sstat == "CT"){
if($totalCost >= 30){
$taxx = round($totalCost * .08875,2);
}elseif($totalCost > 0){
$taxx = round($totalCost * .00475,2);
}}

anymore.

This is the actually numbers for CT state:

Gifts containing candy, cookies, nuts, or any other items besides fruit & vegetables are subject to 6.35% sales tax (not 8.75%).

As you can see and you're right about arrays get complicated! That's why I used fruits & vegetables I feel that is a simple way.

The tax exemption is the fruits:

If the fruit is less than $50 than the tax is at .0 if it's more $50 the tax rate .00635. For the vegatable it's at .00635 sale tax.

I put those numbers in the functions.php and it works! That's why I said it was awesome!

This is the exemption you created:

function getFoodArray(){
$foods = array(
"fruit"=> array("items"=>array(
//Fruit--------------------
'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75,
),"tax_ex_limit"=> 50, "tax_ex_rate"=>0, "tax_rate"=>6.35),

"vegetable"=> array("items"=>array(
//Vegetable--------------------
'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80,
'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80,
),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>6.35));
return $foods;
}

Now I just want to write something like

if($sstat == "CT"){
function getFoodArray(){
$foods = array(
"fruit"=> array("items"=>array(
//Fruit--------------------
'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75,
'A-G01'=>35, 'A-G02'=>50, 'A-G03'=>75,
),"tax_ex_limit"=> 50, "tax_ex_rate"=>0, "tax_rate"=>6.35),

"vegetable"=> array("items"=>array(
//Vegetable--------------------
'A-A01'=>35, 'A-A02'=>55, 'A-A03'=>80,
'B-B01'=>35, 'B-B02'=>55, 'B-B03'=>80,
),"tax_ex_limit"=> false, "tax_ex_rate"=>0, "tax_rate"=>6.35));
return $foods;
}
}

how do I configure:

//CONFIG ARRAY
$foods = getFoodArray();

This is from the checkout sheet:

$cartdata = listItems($input,$_POST['country']);
$cartTotalCost = $cartdata['totalbill'];
$ship = $cartdata['shipping'];
$salesTotal = $cartdata['totalsales'];
$totalTax = $cartdata['totaltax'];
$ordertotal = $cartTotalCost + $express + $gift;

which I don't know how. I just want "CT" to have the sales tax and tax exemption.

So basically, the other 49 states and international countries doesn't apply.

It means that 49 states and international countries can buy anything on the site and the sales tax and tax exemption doesn't apply to them

The domestic & international shipping cost will stay the same. The customer has to choose a country in order for the item to be shipped.

This functions.php works for all kinds of taxes rather than in states or oversee. It's a pain like you said but when you actually see the big picture it really comes in handy.

Member Avatar for LastMitch

Here is the 2nd issue:

The domestic shipping & international shipping:

$domestic = array('United States');

if(in_array($_POST['country'],$domestic)){
//----------Domestic Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
if ($total_sales > 1000){$ship = 25.00;}
}else{
//----------International Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
if ($total_sales > 1000){$ship = 50.00;}
}

The example above you taught me a few weeks back how to write it.

This is the one in the functions.php:

$domestic = array('United States');

if(in_array($ship_country,$domestic)){
//----------Domestic Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
if ($total_sales > 1000){$ship = 25.00;}
}else{
//----------International Shipping--------------//
if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
if ($total_sales > 1000){$ship = 50.00;}
}

When I click submit button to process the shopping cart it won't me let process it instead it changes the domestic shipping cost ($10.50) in to international shipping ($35.00) and stall.

Is there another word for $ship_country? At first I think it identifying the location. But now I think it's not identifying that word so that's the reason why when I click process it change the shipping cost.

I don't know why is does that?

Member Avatar for LastMitch

Here is the 3rd issue:

ItemName.

Is this what you meant:

session_start();
error_reporting(0);
header("Cache-control: private");
include("../include/init.php"); 
if ($_POST["del"] == "yes") {

$sqlpicdel = "SELECT * from items WHERE itemId=".intval($_POST["id"]);
$rspicdel = mysql_query($sqlpicdel);
$rowpicdel = mysql_fetch_array($rspicdel);
$sql="DELETE FROM items WHERE itemId=".$_POST["id"];
$rs= mysql_query($sql);
}
?>
<!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=iso-8859-1" />
<title>MODIFY PRODUCT</title>
<style type="text/css">
<!--
.style1 {color: #FFFFFF}
.style6 {font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 12px; color:white; }
.style3 {font-family: Arial, Helvetica, sans-serif;font-size: 16px;font-weight: bold;
}
-->
</style></head>
<body>
<div align="center">
<p><span class="style3">ADMIN</span></p>
<p><? include("adminmenu.php");?></p>
<table width="1000" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<?php
    $ordBy = 'itemName';
    $ordSe = 'ASC';

if (strlen($_GET['ord']) > 0){
    $ordBy = mysql_real_escape_string($_GET['ord']);
    $ordSe = $_GET['se'] == 'ASC' ? 'ASC' : 'DESC';
    }
$sql="SELECT * FROM items ORDER BY `$ordBy` $ordSe";
$rs= mysql_query($sql) ;

if(!$rs){print "BAD QUERY!!!"; exit();}
if (mysql_num_rows($rs)<1)
{?>
<tr>
<td bgcolor="#FFFFFF" class="style19">&nbsp;</td>
<td bgcolor="#FFFFFF" class="style19">
<div align="center">No Products </div></td>
<td bgcolor="#FFFFFF" class="style19">&nbsp;</td>
<td bgcolor="#FFFFFF" class="style19">&nbsp;</td>
</tr>
<? }else{ ?>   
<tr>
<td width="69" bgcolor="#333333" class="style1 style19">
<div align="left">
<?php if ($_GET['ord']=='sku' and $_GET['se'] == 'ASC'):?>
<a href="allproducts.php?ord=sku&se=DESC">
<span class="style6">SKU</span></a>
<?php else:?>
<a href="allproducts.php?ord=sku&se=ASC">
<span class="style6">SKU</span></a>
<?php endif;?>
</div>
</td>
<td width="351" bgcolor="#333333" class="style1 style19">
<div align="left">
<?php if ($_GET['ord']=='itemName' and $_GET['se'] == 'ASC'):?>
<a href="allproducts.php?ord=itemName&se=DESC">
<span class="style6">Item Name </span></a>
<?php else:?>
<a href="allproducts.php?ord=itemName&se=ASC">
<span class="style6">Item Name </span></a>
<?php endif;?>
</div>
</td>
<td width="208" bgcolor="#333333" class="style1 style19">
<div align="left">
<?php if ($_GET['ord']=='cat' and $_GET['se'] == 'ASC'):?>
<a href="allproducts.php?ord=cat&se=DESC">
<span class="style6">Category</span></a>
<?php else:?>
<a href="allproducts.php?ord=cat&se=ASC">
<span class="style6">Category</span></a>
<?php endif;?>
</div>
</td>
<td width="343" bgcolor="#333333" class="style1 style19">
<div align="left">
<span class="style6">Sub-Category</span></div></td>
</tr>
<? while($row = mysql_fetch_array($rs)){?>
 <tr>
<td colspan="4" bgcolor="#FFFFFF" class="style15">
<form id="form1" name="form1" method="post" action="">
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="0">
<tr>
<td width="7%"><a href="modproduct.php?id=<? echo $row["itemId"]; ?>">
<? echo stripslashes($row["sku"]); ?></a></td>
<td width="36%"><div align="left">
<a href="modproduct.php?id=<? echo $row["itemId"]; ?>">
<? echo stripslashes($row["itemName"]); ?></a></div></td>
<td width="22%"><div align="left">
<? echo stripslashes($row["cat"]); ?></div></td>
<td width="20%"><div align="left">
<? echo stripslashes($row["typ"]); ?></div></td>
<td width="15%"><div align="center">

<input type="submit" name="Submit" value="Delete" />
<input name="del" type="hidden" id="del" value="yes" />
<input name="id" type="hidden" id="id" value="<? echo $row["itemId"]; ?>" />
</div></td></tr></table></form></td>
                      </tr> <? }} ?>
</table>
</p>
</div>
</body>
</html>

or this one:

<?php
session_start();
//fix for ie back button 
header("Cache-control: private");
include("include/init.php");
error_reporting(0);

function can_add_br($string, $afterChar='-', $max=20){
//$chunk_zero = substr($string, 0, strpos($string, $afterChar));
//$chunk_one  = substr($string, strpos($string, $afterChar)+1, strlen($string));

if ( (strpos($string, ' ') > $max) and (strlen($string) > $max) 
and (strpos($string, $afterChar)))
return TRUE;}

function break_word($word, $max=20){
$word = stripslashes($word);
$word = trim($word);

if (can_add_br($word, ':::', $max)){
$word1 = substr($word, 0, strpos($word, ':::'));
$word2 = substr($word, strpos($word, ':::')+1, strlen($word));
return $word1.':::<br/>'.$word2;}

if (can_add_br($word, '::', $max)){
$word1 = substr($word, 0, strpos($word, '::'));
$word2 = substr($word, strpos($word, '::')+1, strlen($word));
return $word1.'::<br/>'.$word2;}

if (can_add_br($word, ':', $max)){
$word1 = substr($word, 0, strpos($word, ':'));
$word2 = substr($word, strpos($word, ':')+1, strlen($word));
return $word1.':<br/>'.$word2;}

if (can_add_br($word, '-', $max)){
$word1 = substr($word, 0, strpos($word, '-'));
$word2 = substr($word, strpos($word, '-')+1, strlen($word));
return $word1.'-<br/>'.$word2;}

return $word;}

function escape_invalid_chars( $str ){$str = str_replace('"', '', $str);

return $str;}

if(empty($_GET['typ'])){$query = "SELECT * FROM coordinate ORDER BY oid";}

if (strlen($_GET['typ']) > 0){$subcat= mysql_real_escape_string($_GET['typ']);
$query = "SELECT * FROM coordinate WHERE `subcat`='$subcat' ORDER BY oid";}

$result = mysql_query($query);
$total_records = mysql_num_rows($result); //the number of records in your result set

$num_cols = 4; //the number of columns
$num_rows = 20; //the number of rows

$num = 0; // don't change this value, this is the 1st number of each record inside a record set

if ($_GET["page"]== "") {$page = 1;
} else {
$page = mysql_real_escape_string($_GET['page']);}

$SearchResult=mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($SearchResult);

$NumberOfResults=mysql_num_rows($SearchResult); 
$Limit     = $num_cols * $num_rows; //Number of results per page
$PageRange = 2; //Number of page links to display before and after current page

$NumberOfPages=ceil($NumberOfResults/$Limit); 

$SearchResult=mysql_query($query." LIMIT " . ($page-1)*$Limit . ",$Limit");
$result=mysql_query($query." LIMIT " . ($page-1)*$Limit . ",$Limit");

$Nav="";
If($page > 1){
$Nav .= "<A HREF=\"catalogc.php?page=" . ($page-1) ."\">
< BACK</A>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";      
}

//Make the ">" link
If($page < $NumberOfPages){
$Nav .= "<A HREF=\"catalogc.php?page=" . ($page+1)."\">
NEXT ></A>&nbsp;&nbsp;&nbsp;"; 
}

//$queryco = "SELECT * FROM coordinate WHERE id = ".$_GET["itemId"];
if ($_GET["itemId"] == ""){
//$itemId = mysql_result($result, $num, "id"); //nothing
}else{

$itemId = intval($_GET["itemId"]);
$queryco = "select * from coordinate where id = ".$itemId;
$resultco = mysql_query($queryco);
$rowco = mysql_fetch_array($resultco);

$itemId = $rowco['item1']; 
$query1 = "select * from items where itemId = ".$itemId;
$result1 = mysql_query($query1);
$row1 = mysql_fetch_array($result1);

$itemId = $rowco['item2'];
$query2 = "select * from items where itemId = ".$itemId;
$result2 = mysql_query($query2);
$row2 = mysql_fetch_array($result2);

$itemId  = $rowco['item3'];
$query3  = "select * from items where itemId = ".$itemId;
$result3 = mysql_query($query3);
$row3    = mysql_fetch_array($result3);

$itemId = $rowco['item4'];
$query4 = "select * from items where itemId = ".$itemId;
$result4 = mysql_query($query4);
$row4 = mysql_fetch_array($result4);

$itemId = $rowco['item5'];
$query5 = "select * from items where itemId = ".$itemId;
$result5 = mysql_query($query5);
$row5 = mysql_fetch_array($result5);
}?>

The last one:

<?
session_start();
header("Cache-control: private");
require_once ('include/init.php');

function can_add_br($string, $afterChar='-', $max=20){
//$chunk_zero = substr($string, 0, strpos($string, $afterChar));
//$chunk_one  = substr($string, strpos($string, $afterChar)+1, strlen($string));

if ( (strpos($string, ' ') > $max) and (strlen($string) > $max) 
and (strpos($string, $afterChar)))
 return TRUE;}

function break_word($word, $max=20){
$word = stripslashes($word);
$word = trim($word);

if (can_add_br($word, ':::', $max)){
$word1 = substr($word, 0, strpos($word, ':::'));
$word2 = substr($word, strpos($word, ':::')+1, strlen($word));
return $word1.':::<br/>'.$word2;}

if (can_add_br($word, '::', $max)){
$word1 = substr($word, 0, strpos($word, '::'));
$word2 = substr($word, strpos($word, '::')+1, strlen($word));
return $word1.'::<br/>'.$word2;}

if (can_add_br($word, ':', $max)){
$word1 = substr($word, 0, strpos($word, ':'));
$word2 = substr($word, strpos($word, ':')+1, strlen($word));
return $word1.':<br/>'.$word2;}

if (can_add_br($word, '-', $max)){
$word1 = substr($word, 0, strpos($word, '-'));
$word2 = substr($word, strpos($word, '-')+1, strlen($word));
return $word1.'-<br/>'.$word2;}
return $word;
}

   $itemcat = mysql_real_escape_string($_GET["cat"]);
   $itemtyp = mysql_real_escape_string($_GET["typ"]);

   if (!isset($_GET["cat"])){header('Location: index.php');}
   $query = "select * from items WHERE cat = '".$itemcat."' AND typ = '".$itemtyp."'  ORDER BY oid";
   if ($itemtyp == "" || $itemtyp == "ALL"){
   $query = "select * from items WHERE cat = '".$itemcat."' ORDER BY oid";}
   $rs = mysql_query($query);

    if (isset($_GET['page'])) {$page = mysql_real_escape_string($_GET['page']);}else {$page = 1;}

    $numRows=mysql_num_rows($rs); 
    if ($itemtyp == "ALL"){$Limit = 150;}else{$Limit = 16;} //Number of results per page
    $PageRange = 12; //Number of page links to display before and after current page

    $NumberOfPages=ceil($numRows/$Limit); 

    $rs=mysql_query($query." LIMIT " . ($page-1)*$Limit . ",$Limit");

    $Nav="";
    //Make the "<<" link
    If($page != 1){
    $Nav .= "<A HREF=\"shop.php?cat=$itemcat&typ=$itemtyp&page=1\">
    << </A>&nbsp;&nbsp;&nbsp;";
    }
    //Make the "<" link
    If($page > 1){
    $Nav .= "<A HREF=\"shop.php?cat=$itemcat&typ=$itemtyp&page=" . ($page-1) ."\">
    <</A>&nbsp;&nbsp;&nbsp;";
    }
For($i = 1 ; $i <= $NumberOfPages ; $i++) { 
If( ($i >= $page - $PageRange && $i <= $page + $PageRange) || ($page<=$PageRange+1 && $i<=2*$PageRange+1) || ($page>=$NumberOfPages-$PageRange && $i>=$NumberOfPages-2*$PageRange-1) )
        {
If($i == $page && $NumberOfPages != 1) { $Nav .= "<B>$i</B>&nbsp;&nbsp;&nbsp;"; 
}Else If ($i != $page && $i != 1){ 
$Nav .= "<A HREF=\"shop.php?cat=$itemcat&typ=$itemtyp&page=" . $i ."\">$i</A>&nbsp;&nbsp;&nbsp;";
}Else If ($i != $page && $i == 1){ 
$Nav .= "<A HREF=\"shop.php?cat=$itemcat&typ=$itemtyp&page=" . $i ."\">$i</A>&nbsp;&nbsp;&nbsp;";
            }}}
    //Make the ">" link
If($page < $NumberOfPages){
$Nav .= "<A HREF=\"shop.php?cat=$itemcat&typ=$itemtyp&page=" . ($page+1) ."\"> ></A>&nbsp;&nbsp;&nbsp;";
    }
    //Make the ">>" link
    If($page < $NumberOfPages){
        $Nav .= "<A HREF=\"shop.php?cat=$itemcat&typ=$itemtyp&page=" . $NumberOfPages ."\"> >></A>&nbsp;&nbsp;&nbsp;";
    }
    ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SHOP: <?=$_GET["cat"];?></title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
<? include("header.php");?>
<table width="640" style="position:relative; top:-50px;" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="669" valign="top">
<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC">
<tr>
<td width="27%" height="36" valign="top" bgcolor="#FFFFFF" class="navtitle" style=" padding-top:43px">          </td>
<td valign="top" bgcolor="#FFFFFF"><? if ($page>1) {$pagestart =  ($_GET['page']-1)*$Limit;}
if ($page==1) {$pagestart = 0;}?>
<br>
<div align="center" class="navtitle">
<?="PAGE $page OF $NumberOfPages"; if ($numRows != 0) {
echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;". $Nav; }?>
&nbsp;&nbsp;</div></td>
</tr>
<tr>
<td height="150" valign="top" bgcolor="#FFFFFF" class="navtitle" style="padding-top:12px; width:150px;">
<?php include("include/menuinc.php"); ?>
</td>
 <td height="700" valign="top" bgcolor="#FFFFFF">
 <?php if ($page>1) {$pagestart =  ($_GET['page']-1)*$Limit;} if ($page==1) {$pagestart = 0;}?>
<table align="left" cellpadding="0" cellspacing="0">
<tr>
<?php $a = 0; while ($row = mysql_fetch_array($rs)) { if ($a % 4 == 0) { ?>
</tr>
<tr><td height="4" colspan="4">&nbsp;</td></tr>
<tr>
<? } ?>
<td valign="top" align="center" class="navtitlesm" style="width:110px; word-wrap:break-word; border:none; border-spacing:0px;">
<a href="product-detail.php?id=<? echo $row["itemId"]; ?>&cat=<?=$_GET["cat"]?>">
<img align="absmiddle" hspace="5" vspace="0" src="upload/<? echo $row["im1"]; ?> " width="110" height="110" border="0" />
</a>
<br/> 
<a style="width:110px; word-wrap:break-word; display:block; text-transform:uppercase;" href="product-detail.php?id=<? echo $row["itemId"]; ?>&cat=<?=$_GET["cat"]?>">
<?php 
$itemName = strlen($row['itemName']) > 20 ? break_word($row['itemName']) : stripslashes($row["itemName"]);
echo $itemName ; ?>
</a> 
</td>
<? $a++; } ?>
</tr>
</table></td>
</tr>
<tr>
<td height="29" valign="top" bgcolor="#FFFFFF" class="navtitle"></td>
<td valign="top" bgcolor="#FFFFFF"><? if ($page>1) {$pagestart =  ($_GET['page']-1)*$Limit;}
if ($page==1) {$pagestart = 0;}?>
<br>
<div align="center" class="navtitle">
<?="PAGE $page OF $NumberOfPages"; if ($numRows != 0) {echo "&nbsp;&nbsp;&nbsp;&nbsp;". $Nav; }?>
 &nbsp;&nbsp;</div></td>
</tr>
</table>
</td>
 <td width="1"><p align="center"><br>
</p>
</td>
</tr>
</table>
<p>&nbsp;</p>
<? include("footer.php");?>                   
</body>
</html>

These are the products details. I divide it into 3 files. Tell me which one is the one that can put that in the array?

I apologize for the files It's lot of data.

I appreciated that you taking your time to help me out again!

I appreciate your insight again!

This bit looks good SELECT * from items WHERE itemId=".intval($_POST["id"])

I should really have just made a project with your files by now so i dont have to keep copying them!

You don't seem to be that aware of your mysql data, mysql is a very powerful way of being able to store data and use it in very specific ways for what you happen to need it for.

If you want to see all the data stored on your items you can hopefully just copy this page and save it with a new name then open it, id just ignore trying to understand it it basically just loops through all the data pulled from mysql and formats it as a csv

exportcsv.php

<?php
session_start();
header("Cache-control: private");
require_once ('include/init.php');
require_once ('include/functions.php');

$query = "SELECT * from items";
$result = mysql_query($query) or die(mysql_error());
if($result !== false){
    while ($row=mysql_fetch_assoc($result)) {
        if($n == 0){
            $htmlheaders = "<tr>\r\n";
            $htmldata = "<tr>\r\n";
            $i = 0;
            foreach($row as $k=>$v){
                if($i == 0){
                    $i++;
                    $headers = $k;
                    $htmlheaders .= "<th>{$k}</th>\r\n";
                    $data = '"'.str_replace('"',"'",$v).'"';
                    $htmldata .= "<td>{$v}</td>\r\n";
                }else{
                    $headers .= ",{$k}";
                    $htmlheaders .= "<th>{$k}</th>\r\n";
                    $data .= ',"'.str_replace('"',"'",$v).'"';
                    $htmldata .= "<td>{$v}</td>\r\n";
                }
            }
            $headers .= "\r\n";
            $htmlheaders .= "</tr>\r\n";
            $data .= "\r\n";
            $htmldata .= "</tr>\r\n";
        }else{
            $htmldata .= "<tr>\r\n";
            $i = 0;
            foreach($row as $k=>$v){
                if($i == 0){
                    $i++;
                    $data .= '"'.str_replace('"',"'",$v).'"';
                    $htmldata .= "<td>{$v}</td>\r\n";
                }else{
                    $data .= ',"'.str_replace('"',"'",$v).'"';
                    $htmldata .= "<td>{$v}</td>\r\n";
                }
            }
            $data .= "\r\n";
            $htmldata .= "</tr>\r\n";
        }
        $n++;
    }
}else{
    echo "invalid result returned";
}
//$n == number of rows
echo $headers.$data;//csv
//echo "<table>\r\n{$htmlheaders}{$htmldata}</table>";//html
?>

I just mention that because i don't know what data might be in there and what the number in your array comes from: 'A-C01'=>35, 'A-C02'=>50, 'A-C03'=>75<- this number, this is what the function will look like - much smaller and you can have 10,000 items if you like!

function getFoodArray(){
    $query = "SELECT * from items";//pulls all data in the items table
    $result = mysql_query($query) or die(mysql_error());//run query on the mysql server, end the script and show the error message on error
    if($result !== false){//if a mysql query errors or pulls no data it returns false
        //$result has some data
        $foods = array();//declare empty $foods array
        while($row = mysql_fetch_assoc($result)){//loop through every item pulled from mysql table, $row contains all the data for each item and is an array
            $foods[$row['cat']]['items'][$row['itemId']] = $row['some_number'];
            //tell it to insert each item into the foods array
            //first by category, into items, then referenced by the itemId
            //eg. $foods['fruit']['items']['A-C01'] = 35;
        }
    }else{
        //$result has no data
        $foods = false;
    }
    return $foods;//send the $foods variable back as the result of the function
}

I think ill have to separate the tax out of ardav's function now cause its not really been written in mind to having so many variables on the tax.

see if you can get data or the field names out of the database using that while i try get time to do it

Member Avatar for LastMitch

@Biiim

I'll try to run the script and get the data out. As you notice I'm not familiar with mysql data but it's good to learn how it function works now. I appreciate your insight again!

Heres a new function to add into the functions.php file:

function getTax($taxcode,$cat,$amount){
        if((!ctype_digit($amount) && !is_int($amount)) || $amount < 0){
            //not a number or less than 0, exit
            return false;
        }
        if($amount == 0){//return 0 tax if no value
            return 0;
        }

        if($taxcode == 'CT'){//Crown Colony, tell it how to work out tax for this state
            if($cat == 'Fruit'){//if crown colony and fruit
                if($amount > 50){//if crown colony and fruit value over $50 
                    $tax = round($amount * .0635,2);
                }else{//crown colony and fruit under $50
                    $tax = 0;
                }
            }elseif($cat == 'vegetable'){//crown colony vegetables
                //Gifts containing candy, cookies, nuts, or any other items besides fruit & vegetables are subject to 6.35% sales tax (not 8.75%).
                //means vegetables are full 8.75% tax?
                $tax = round($amount * .0875,2);
            }else{//unknown category in crown colony
                $tax = round($amount * .0875,2);
            }
        }else{//any unspecified taxcode, apply a general tax rate
            $tax = round($amount * .0875,2);
        }
        return $tax;
    }

And then the listItem function needs updating:

function listItems($input,$ship_country,$taxcode){
    //CONFIG ARRAY
    $foods = getFoodArray();
    $foodKeyArray = getFoodKeyArray();
     //VARIABLES
    $running = array('fruit'=>0,'vegetable'=>0);
    $output = array('fruit'=>'','vegetable'=>'');
    $tax = array('fruit'=>0,'vegetable'=>0);
    //LOOP THROUGH INPUT
    foreach($input as $item){
        $key = $item[0];
        $qty = $item[1];
        if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
            $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
            $unit = $foods[$type]['items'][$key];
            $cost = number_format($qty * $unit,2);
            $output[$type] .= "<tr><td>$foodKeyArray[$key]</td><td>$qty</td><td>$unit</td><td class=\"right\">$cost</td></tr>";
            $running[$type] += $cost;
        }
    }
    //DO TOTALS FOR OUTPUT
    //1) Tax
    $tax['fruit'] = getTax($taxcode, 'Fruit', $running['fruit']);
    $fruit_tax_label = (($tax['fruit']/$running['fruit'])*100).'%';//work out tax applied

    $tax['vegetable'] = getTax($taxcode, 'vegetable', $running['vegetable']);
    $vegetable_tax_label = (($tax['vegetable']/$running['vegetable'])*100).'%';//work out tax applied

    $total_tax = $tax['fruit'] + $tax['vegetable'];
    //2) Sales Total
    $total_sales = $running['vegetable'] + $running['fruit'];
    //3) Shipping
    $domestic = array('United States');
    if(in_array($ship_country,$domestic)){
        //----------Domestic Shipping--------------//
        if ($total_sales > 0 && $total_sales <= 100){$ship = 6.50;}
        if ($total_sales > 100 && $total_sales <= 300){$ship = 10.50;}
        if ($total_sales > 300 && $total_sales <= 500){$ship = 14.00;}
        if ($total_sales > 500 && $total_sales <= 700){$ship = 18.00;}
        if ($total_sales > 700 && $total_sales <= 1000){$ship = 20.00;}
        if ($total_sales > 1000){$ship = 25.00;}
    }else{
        //----------International Shipping--------------//
        if ($total_sales > 0 && $total_sales <= 100){$ship = 30.00;}
        if ($total_sales > 100 && $total_sales <= 300){$ship = 35.00;}
        if ($total_sales > 300 && $total_sales <= 500){$ship = 40.00;}
        if ($total_sales > 500 && $total_sales <= 700){$ship = 45.00;}
        if ($total_sales > 700 && $total_sales <= 1000){$ship = 50.00;}
        if ($total_sales > 1000){$ship = 50.00;}
    }
    //4) Bill Total
    $total_bill = $total_sales + $total_tax + $ship;
    //BUILD TOTAL HTML
    $total =
    "<tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Fruits</td><td class=\"right\">" . number_format($running['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Vegetables</td><td class=\"right\">" . number_format($running['vegetable'],2) . "</td></tr>
    <tr><td colspan=\"3\">Total Sales</td><td class=\"right\">" . number_format($total_sales,2) . "</td></tr>
    <tr><td colspan=\"3\">Shipping Cost</td><td class=\"right\">" . number_format($ship,2) . "</td></tr>

    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Fruit Tax @ $fruit_tax_label</td><td class=\"right\">" . number_format($tax['fruit'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Vegetable Tax @ $vegetable_tax_label</td><td class=\"right\">" . number_format($tax['vegetable'], 2) . "</td></tr>
    <tr><td colspan=\"3\">Total Tax</td><td class=\"right\">" . number_format($total_tax, 2) . "</td></tr>
    <tr><td colspan=\"4\"><hr /></td></tr>
    <tr><td colspan=\"3\">Total Bill</td><td class=\"right\">" . number_format($total_bill, 2) . "</td></tr>";
    $returndata = array();
    $returndata['html'] = "<tr><th>ITEM</th><th>QTY</th><th>UNIT/\$</th><th>COST/\$</th></tr>" . $output['fruit'] . $output['vegetable'] . $total;
    $returndata['veg_tax_label'] = $vegetable_tax_label;
    $returndata['fruit_tax_label'] = $fruit_tax_label;
    $returndata['shipping'] = $ship;
    $returndata['totaltax'] = $total_tax;
    $returndata['totalsales'] = $total_sales;
    $returndata['totalbill'] = $total_bill;
    return $returndata;
}

And heres the updated getFoodKeyArray function, i'm pretty sure this one will just work

function getFoodKeyArray(){
    $query = "SELECT * from items";//pulls all data in the items table
    $result = mysql_query($query) or die(mysql_error());//run query on the mysql server, end the script and show the error message on error
    if($result !== false){//if a mysql query errors or pulls no data it returns false
        //$result has some data
        $foodKeyArray = array();//declare empty array
        while($row = mysql_fetch_assoc($result)){//loop through every item pulled from mysql table, $row contains all the data for each item and is an array
            $foodKeyArray[$row['itemId']] = $row['itemName'];
            //tell it to insert an entry with a index of the itemId and the value the items name
        }
    }else{
        //$result has no data
        $foodKeyArray = false;
    }
    return $foodKeyArray;
}

and then the call to the listItems function needs to pass the $sstat variable, that i decided to call taxcode in the tax function since i figured you could use it for any variation of tax:

$cartdata = listItems($input,$_POST['country'],$sstat);

Hope thats understandable for you. I'm not suprised them pages are doing your head it, they are all quite badly formatted.

You should check out zend studio if you are going to be editing php for awhile - it will validate your code and you can track variables around the page and even jump to where a function is declared, it can be a bit heavy to get it setup though - i've been using it for 2/3 years now i've still never bothered to get a php server setup for it haha

commented: Thanks for the new functions for me to run on +0
Member Avatar for LastMitch

Hi Biiim,

My internet went down the whole day. I finally got it working again. I used that script to test out the database. I put that file on the server and I ran it and it pop out alot of data mostly fruits and vegetables! You're right about the pages. I think I should start learning some new skills about php. I still used XAMPP after all these years. I never heard of zend studio but I did went to the website check out info and maybe I'll download if it's not that hard to installed. I think that has be the best advice I had in a long time. I'll run the other scripts over the weekend and see how the scripts work and thanks again!

Mitch

Member Avatar for LastMitch

@Biiim

The getTax Function doesn't work. I don't think it pick up the $amount.

I'm also having issue with this:

   <input name="place" type="hidden" id="place" value="yes" />
   <input name="tcost" type="hidden" id="tcost" value="<? echo $totalCost; ?>" />
   <input name="ship" type="hidden" id="ship" value="<? echo $ship; ?>" />
   <input name="taxx" type="hidden" id="taxx" value="<? echo $totalTax; ?>" />
   <input type="submit" name="Submit" value="Place Order" />

In my shopping cart I have my items and taxes and shipping.

When I press "Submit", it won't "Place Order" instead it stalled and the shipping cost changes from domestic shipping to international shipping? I can't figure it out. I switch the old file back to see and adjust and I adjust it to look the same and it still won't process.

I think the problem is here (but I don't know which one?):

$cartdata = listItems($input,$_POST['country']);
$cartTotalCost = $cartdata['totalbill'];
$ship = $cartdata['shipping'];
$salesTotal = $cartdata['totalsales'];
$totalTax = $cartdata['totaltax'];
$ordertotal = $cartTotalCost + $express + $gift;
//----------store important values in session--------------//
$_SESSION['tcost'] = $totalCost;
$_SESSION['ship'] = $ship;
$_SESSION['taxx'] = $totalTax;
//----------store important values in session--------------//
echo $cartdata['html']

I just need to isolate that issue maybe I can see code in action and start running the script so I can modify the code and I would know where to fixed the that issue.

I appreciate your insight again!

Member Avatar for LastMitch

@biiim,

I'm almost done!! I'm so excited! I was working on this for the whole weekend. Everything works fine

I couldn't figure out the getTax function. So I went back to the Arrays files.

For the item name, I finally figure it out how to put the ItemName

$row['itemName'] into the $input[ ]
$input[ ] = array($row['itemId'],$row['qty']);

This is what I put for the $input[ ]

$input[] = array($row['itemId''],$row['itemName'],$row['qty']);

This is what I put in the functions.php file:

foreach($input as $item){
    $key = $item[0];
    $name = $item[1];
    $qty = $item[2];
    if(isset($foods['fruit']['items'][$key]) || isset($foods['vegetable']['items'][$key])){
    $type = (isset($foods['fruit']['items'][$key])) ? 'fruit' : 'vegetable';
    $price = $foods[$type]['items'][$key];
    $cost = number_format($qty * $price,2);
    $output[$type] .= "<tr><td><font face='Helvetica, sans-serif' size='2'>$key</font></td><td><font face='Helvetica, sans-serif' size='2'>$name</font></td><td><font face='Helvetica, sans-serif' size='2'>$qty</font></td><td class=\"right\"><font face='Helvetica, sans-serif' size='2'>$$cost</font></td></tr>";
    $running[$type] += $cost;

As you can see I added an $name as a $item and it appear! I don't know why maybe I think you do because you have a lot of experience in this but it work!

For the taxes in state = CT:

This what I did:

if($sstat == 'CT'){ 

if($foods['fruit']['tax_ex_limit'] && $running['fruit'] < $foods['fruit']['tax_ex_limit']){
$tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_ex_rate']/100;
$fruit_tax_label = $foods['fruit']['tax_ex_rate'] . "%";
}else{
$tax['fruit'] = $running['fruit'] * $foods['fruit']['tax_rate']/100;
$fruit_tax_label = $foods['fruit']['tax_rate'] . "%";
}
if($foods['vegetable']['tax_ex_limit'] && $running['vegetable'] < $foods['vegetable']['tax_ex_limit']){
$tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_ex_rate']/100;
$vegetable_tax_label = $foods['vegetable']['tax_ex_rate'] . "%";
}else{
$tax['vegetable'] = $running['vegetable'] * $foods['vegetable']['tax_rate']/100;
$vegetable_tax_label = $foods['vegetable']['tax_rate'] . "%";
}

}

This is what I put is what you put in function and $cartdata:

function listItems($input,$ship_country,$sstat)

$cartdata = listItems($input,$_POST['country'],$sstat);

and it work it actually isolate that state!

This is the only issue is that I have left:

<input name="place" type="hidden" id="place" value="yes" />
<input name="tcost" type="hidden" id="tcost" value="<? echo $totalCost; ?>" />
<input name="ship" type="hidden" id="ship" value="<? echo $ship; ?>" />
<input name="taxx" type="hidden" id="taxx" value="<? echo $totalTax; ?>" />
<input type="submit" name="Submit" value="Place Order" />

In my shopping cart I have my items and taxes and shipping.

When I press "Submit", it won't "Place Order" instead it stalled and the shipping cost changes from domestic shipping to international shipping? I can't figure it out. I switch the old file back to see and adjust and I adjust it to look the same and it still won't process.

The shipping itself is working because when I choose a state it's domestic and other countries is international!

I know you have a good eye, can you see why the "Place Order" is not working properly. When I put my old original file back on my server it works fines.

The 2 files I used is from the one on page '2' that you posted on the bottom and I used a few lines from above to make this work.

I can't believe it's a month, I been working on this for a month! I just want to 'Thank You' for not giving up on me and helping me out with this. The only issue I have left is that submit button.

I appreciate your insight again! It like you what you said work what I have and I did!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.