Jump to content

php weight calculation


desmond_ckl

Recommended Posts

Hi there, i follow a tutorial from www.phpwebcommerce.com and i'm trying to customize the shipping cost based on product weight instead of flat rate. This tutorial original setting for shipping cost is in checkout-function.php , which i just set a value to define the flat rate shipping. And the miniCart.php file is showing all the calculation. I'm trying to customize the code by doing this:

In my database, table product...i add a new field call pd_weight and insert weight for the product then

common.php i add a new function "CalculateShippingCost()" . In checkout-function.php i modified "function getOrderAmount($orderId)" & i guess in miniCart.php i need to remove "$shopConfig" and replace some coding but im really confuse. I'm not sure all the coding i customize is it correct. Please help me....any help will very appreciate! Thx a million.

 

common.php

<?php
/*
Contain the common functions 
required in shop and admin pages
*/
require_once 'config.php';
require_once 'database.php';

/*
Make sure each key name in $requiredField exist
in $_POST and the value is not empty
*/
function checkRequiredPost($requiredField) {
$numRequired = count($requiredField);
$keys        = array_keys($_POST);

$allFieldExist  = true;
for ($i = 0; $i < $numRequired && $allFieldExist; $i++) {
	if (!in_array($requiredField[$i], $keys) || $_POST[$requiredField[$i]] == '') {
		$allFieldExist = false;
	}
}

return $allFieldExist;
}

function getShopConfig()
{
// get current configuration
$sql = "SELECT sc_name, sc_address, sc_phone, sc_email, sc_shipping_cost, sc_order_email, cy_symbol 
		FROM tbl_shop_config sc, tbl_currency cy
		WHERE sc_currency = cy_id";
$result = dbQuery($sql);
$row    = dbFetchAssoc($result);

    if ($row) {
        extract($row);

        $shopConfig = array('name'           => $sc_name,
                            'address'        => $sc_address,
                            'phone'          => $sc_phone,
                            'email'          => $sc_email,
			            'sendOrderEmail' => $sc_order_email,
                            'shippingCost'   => $sc_shipping_cost,
                            'currency'       => $cy_symbol);
    } else {
        $shopConfig = array('name'           => '',
                            'address'        => '',
                            'phone'          => '',
                            'email'          => '',
			            'sendOrderEmail' => '',
                            'shippingCost'   => '',
                            'currency'       => '');    
    }

return $shopConfig;						
}


/*********************** Function Shipping Cost  **************************************/
function CalculateShippingCost()
{

// get current configuration
$sql = "SELECT pd_weight
		FROM tbl_product
	   ";

$result = dbQuery($sql);
$row    = dbFetchAssoc($result);

    if ($row) {
        extract($row);



$weightTotal = $pd_weight * $od_qty;

			/////////////////////West Malaysia ///////////////////////////////
if($weightTotal == 0.25 & country == "WestMalysia") ///250gram or 0.25kg
                {
                        $conclusion = 6;//your shipping Price
                }

                else if($weightTotal == 0.5 & country == "WestMalysia")  ///500gram or 0.5kg
                {
                        $conclusion = 6;//your shipping Price
                }

			 else if($weightTotal == 0.75 & country == "WestMalysia")  ///750gram or 0.75kg
                {
                        $conclusion = 7;//your shipping Price
                }

			 else if($weightTotal == 1 & country == "WestMalysia")
                {
                        $conclusion = 8;//your shipping Price
                }

			 else if($weightTotal == 1.25 & country == "WestMalysia")
                {
                        $conclusion = 9;//your shipping Price
                } 

			else if($weightTotal == 1.5 & country == "WestMalysia")
                {
                        $conclusion = 11;//your shipping Price
                } 

			else if($weightTotal == 1.75 & country == "WestMalysia")
                {
                        $conclusion = 12;//your shipping Price
                }

			 else if($weightTotal == 2 & country == "WestMalysia")
                {
                        $conclusion = 13;//your shipping Price
                }

			/////////////////////EAST Malaysia ///////////////////////////////
                else if($weightTotal == 0.25 & country == "EastMalysia")
                {
                        $conclusion = 9;//your shipping Price
                }

			else if($weightTotal == 0.5 & country == "EastMalysia")
                {
                        $conclusion = 9;//your shipping Price
                }

			else if($weightTotal == 0.75 & country == "EastMalysia")
                {
                        $conclusion = 11;//your shipping Price
                }

			else if($weightTotal == 1 & country == "EastMalysia")
                {
                        $conclusion = 14;//your shipping Price
                }

			else if($weightTotal == 1.25 & country == "EastMalysia")
                {
                        $conclusion = 17;//your shipping Price
                }

			else if($weightTotal == 1.5 & country == "EastMalysia")
                {
                        $conclusion = 19;//your shipping Price
                }

			else if($weightTotal == 1.75 & country == "EastMalysia")
                {
                        $conclusion = 22;//your shipping Price
                }

			else if($weightTotal ==2 & country == "EastMalysia")
                {
                        $conclusion = 14;//your shipping Price
                }


			return $weightTotal;


}
/*******************************************************************************/




function displayAmount($amount)
{
global $shopConfig;
return $shopConfig['currency'] . number_format($amount);
}

/*
Join up the key value pairs in $_GET
into a single query string
*/
function queryString()
{
$qString = array();

foreach($_GET as $key => $value) {
	if (trim($value) != '') {
		$qString[] = $key. '=' . trim($value);
	} else {
		$qString[] = $key;
	}
}

$qString = implode('&', $qString);

return $qString;
}

/*
Put an error message on session 
*/
function setError($errorMessage)
{
if (!isset($_SESSION['db_desmond_error'])) {
	$_SESSION['db_desmond_error'] = array();
}

$_SESSION['db_desmond_error'][] = $errorMessage;

}

/*
print the error message
*/
function displayError()
{
if (isset($_SESSION['db_desmond_error']) && count($_SESSION['db_desmond_error'])) {
	$numError = count($_SESSION['db_desmond_error']);

	echo '<table id="errorMessage" width="550" align="center" cellpadding="20" cellspacing="0"><tr><td>';
	for ($i = 0; $i < $numError; $i++) {
		echo '&#8226; ' . $_SESSION['db_desmond_error'][$i] . "<br>\r\n";
	}
	echo '</td></tr></table>';

	// remove all error messages from session
	$_SESSION['db_desmond_error'] = array();
}
}

/**************************
Paging Functions
***************************/

function getPagingQuery($sql, $itemPerPage = 10)
{
if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
	$page = (int)$_GET['page'];
} else {
	$page = 1;
}

// start fetching from this row number
$offset = ($page - 1) * $itemPerPage;

return $sql . " LIMIT $offset, $itemPerPage";
}

/*
Get the links to navigate between one result page to another.
Supply a value for $strGet if the page url already contain some
GET values for example if the original page url is like this :

http://www.phpwebcommerce.com/plaincart/index.php?c=12

use "c=12" as the value for $strGet. But if the url is like this :

http://www.phpwebcommerce.com/plaincart/index.php

then there's no need to set a value for $strGet


*/
function getPagingLink($sql, $itemPerPage = 10, $strGet = '')
{
$result        = dbQuery($sql);
$pagingLink    = '';
$totalResults  = dbNumRows($result);
$totalPages    = ceil($totalResults / $itemPerPage);

// how many link pages to show
$numLinks      = 10;


// create the paging links only if we have more than one page of results
if ($totalPages > 1) {

	$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;


	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$pageNumber = (int)$_GET['page'];
	} else {
		$pageNumber = 1;
	}

	// print 'previous' link only if we're not
	// on page one
	if ($pageNumber > 1) {
		$page = $pageNumber - 1;
		if ($page > 1) {
			$prev = " <a href=\"$self?page=$page&$strGet/\">[Prev]</a> ";
		} else {
			$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
		}	

		$first = " <a href=\"$self?$strGet\">[First]</a> ";
	} else {
		$prev  = ''; // we're on page one, don't show 'previous' link
		$first = ''; // nor 'first page' link
	}

	// print 'next' link only if we're not
	// on the last page
	if ($pageNumber < $totalPages) {
		$page = $pageNumber + 1;
		$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
		$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
	} else {
		$next = ''; // we're on the last page, don't show 'next' link
		$last = ''; // nor 'last page' link
	}

	$start = $pageNumber - ($pageNumber % $numLinks) + 1;
	$end   = $start + $numLinks - 1;		

	$end   = min($totalPages, $end);

	$pagingLink = array();
	for($page = $start; $page <= $end; $page++)	{
		if ($page == $pageNumber) {
			$pagingLink[] = " $page ";   // no need to create a link to current page
		} else {
			if ($page == 1) {
				$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
			} else {	
				$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
			}	
		}

	}

	$pagingLink = implode(' | ', $pagingLink);

	// return the page navigation link
	$pagingLink = $first . $prev . $pagingLink . $next . $last;
}

return $pagingLink;
}
?>

 

miniCart.php


<?php
if (!defined('WEB_ROOT')) {
exit;
}

$cartContent = getCartContent();

$numItem = count($cartContent);	
?>
<table width="180" border="0" cellspacing="0" cellpadding="4" id="minicart" >
  
<?php
if ($numItem > 0) {
?>
<tr>
  <td colspan="2" class="black_txt_2">Cart Content</td>
</tr>
<?php
$subTotal = 0;
for ($i = 0; $i < $numItem; $i++) {
	extract($cartContent[$i]);
	$pd_name = "$ct_qty x $pd_name";
	$url = "index.php?c=$cat_id&p=$pd_id";

	$subTotal += $pd_price * $ct_qty;
?>
<tr>
   <td width="73%" ><a href="<?php echo $url; ?>"><span class="green_txt_2"><?php echo $pd_name; ?></span></a></td>
   
  <td width="27%" align="right" class="black_txt_2"><?php echo displayAmount($ct_qty * $pd_price); ?></td>
</tr>
<?php
} // end while
?>
  <tr><td align="right" class="black_txt_2">Sub-total</td>
  <td width="27%" align="right" class="black_txt_2"><?php echo displayAmount($subTotal); ?></td>
</tr>
  <tr><td align="right"  class="black_txt_2">Shipping</td>
  <td width="27%" align="right" class="black_txt_2"><?php echo displayAmount($shopConfig['shippingCost']); ?></td>
</tr>
  <tr><td align="right" class="black_txt_2"><strong>Total</strong></td>
  <td width="27%" align="right" class="black_txt_2"><strong><?php echo displayAmount($subTotal + $shopConfig['shippingCost']); ?></strong></td>
</tr>
  <tr><td colspan="2"> </td></tr>
  <tr>
  <td colspan="2" align="center" class="black_txt_2"><a href="cart.php?action=view"> <img src="images/btn_proceedtocheckout.gif" ></a></td>
</tr>  
<?php	
} else {
?>
  <tr><td colspan="2" align="center" valign="middle" class="black_txt_2">Shopping Cart Is Empty</td></tr>
<?php
}
?> 
</table>


 

 

checkout-functions.php

<?php
require_once 'config.php';

/*********************************************************
*                 CHECKOUT FUNCTIONS 
*********************************************************/
function saveOrder()
{
$orderId       = 0;
$shippingCost  = 5;
$requiredField = array('hidShippingFirstName', 'hidShippingLastName', 'hidShippingAddress1', 'hidShippingCity', 'hidShippingPostalCode',
					   'hidPaymentFirstName', 'hidPaymentLastName', 'hidPaymentAddress1', 'hidPaymentCity', 'hidPaymentPostalCode');
					   
if (checkRequiredPost($requiredField)) {
    extract($_POST);

	// make sure the first character in the 
	// customer and city name are properly upper cased
	$hidShippingFirstName = ucwords($hidShippingFirstName);
	$hidShippingLastName  = ucwords($hidShippingLastName);
	$hidPaymentFirstName  = ucwords($hidPaymentFirstName);
	$hidPaymentLastName   = ucwords($hidPaymentLastName);
	$hidShippingCity      = ucwords($hidShippingCity);
	$hidPaymentCity       = ucwords($hidPaymentCity);

	$cartContent = getCartContent();
	$numItem     = count($cartContent);

	// save order & get order id
	$sql = "INSERT INTO tbl_order(od_date, od_last_update, od_shipping_first_name, od_shipping_last_name, od_shipping_address1, 
	                              od_shipping_address2, od_shipping_phone, od_shipping_state, od_shipping_city, od_shipping_postal_code, od_shipping_cost,
                                      od_payment_first_name, od_payment_last_name, od_payment_address1, od_payment_address2, 
								  od_payment_phone, od_payment_state, od_payment_city, od_payment_postal_code)
                VALUES (NOW(), NOW(), '$hidShippingFirstName', '$hidShippingLastName', '$hidShippingAddress1', 
			        '$hidShippingAddress2', '$hidShippingPhone', '$hidShippingState', '$hidShippingCity', '$hidShippingPostalCode', '$shippingCost',
					'$hidPaymentFirstName', '$hidPaymentLastName', '$hidPaymentAddress1', 
					'$hidPaymentAddress2', '$hidPaymentPhone', '$hidPaymentState', '$hidPaymentCity', '$hidPaymentPostalCode')";
	$result = dbQuery($sql);

	// get the order id
	$orderId = dbInsertId();

	if ($orderId) {
		// save order items
		for ($i = 0; $i < $numItem; $i++) {
			$sql = "INSERT INTO tbl_order_item(od_id, pd_id, od_qty)
					VALUES ($orderId, {$cartContent[$i]['pd_id']}, {$cartContent[$i]['ct_qty']})";
			$result = dbQuery($sql);					
		}


		// update product stock
		for ($i = 0; $i < $numItem; $i++) {
			$sql = "UPDATE tbl_product 
			        SET pd_qty = pd_qty - {$cartContent[$i]['ct_qty']}
					WHERE pd_id = {$cartContent[$i]['pd_id']}";
			$result = dbQuery($sql);					
		}


		// then remove the ordered items from cart
		for ($i = 0; $i < $numItem; $i++) {
			$sql = "DELETE FROM tbl_cart
			        WHERE ct_id = {$cartContent[$i]['ct_id']}";
			$result = dbQuery($sql);					
		}							
	}					
}

return $orderId;
}

/*
Get order total amount ( total purchase + shipping cost )
*/
function getOrderAmount($orderId)
{
$orderAmount = 0;
											    ///ORIGINAL///
									/////////SELECT SUM (pd_price * od_qty) /////		
$sql = "SELECT SUM(pd_price * [od_qty * pd_weight] ) 
        FROM tbl_order_item oi, tbl_product p 
	    WHERE oi.pd_id = p.pd_id and oi.od_id = $orderId

		UNION

		SELECT pd_weight
		FROM tbl_product
		WHERE oi.pd_id = p.pd_id ";  ////?????


		/***********ORIGINAL************
		SELECT od_shipping_cost 
		FROM tbl_order
		WHERE od_id = $orderId";
		********************************/

$result = dbQuery($sql);

if (dbNumRows($result) == 2) {
	$row = dbFetchRow($result);
	$totalPurchase = $row[0];

	$row = dbFetchRow($result);
	$weightTotal = $row[0];						    /******original***** $shippingCost = $row[0]; **************/

	$orderAmount = $totalPurchase + $weightTotal;  /*****original****** $totalPurchase + $shippingCost ***********/
}	

return $orderAmount;	
}

?>

 

 

Link to comment
Share on other sites

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

Join the conversation

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

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

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

×   Your previous content has been restored.   Clear editor

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

×
×
  • Create New...

Important Information

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