I'm using a shopping cart script from a tutorial I came across a while ago, and I need to modify it to calculate sales tax for my state (Pennsylvania). I want it to extract the state, compare it to either Pennsylvania or PA incase someone writes the state shorthand and then multiply the subtotal (for the items.. before shipping is added) by the sales tax for this state and add that to the subtotal. How should I go about doing this? Here is the script that does the calculation for grand total.
<?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;
$sql = "SELECT SUM(pd_price * od_qty)
FROM tbl_order_item oi, tbl_product p
WHERE oi.pd_id = p.pd_id and oi.od_id = $orderId
UNION
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);
$shippingCost = $row[0];
$orderAmount = $totalPurchase + $shippingCost;
}
return $orderAmount;
}
?>
You don't have to handle differing tax rates per municipality? Normally this would be looked up from a tax table by zip code, and maybe even for the street address + zip code (in some states).
It would look like this:
// is it a Pennsylvania zip code?
if ($zipcode < 15000 || $zipcode > 19699) // needs verification of the actual range
$taxrate = 0;
else
{
$rs = mysql_query ("select rate from taxtable where zipcode = '$zipcode'", $db);
if (!$rs)
{
// error looking up rate, maybe apply a default?
}
else
{
$row = mysql_fetch_assoc($rs);
$taxrate = $row['rate'];
}
}
$amount = $amount * (1 + $taxrate / 100.0);
Related
I have a 200 inputs ( 200 rows ) in my web page , the back end user some time enter 20 or 50 inputs and left the rest empty
how to prevent empty inputs from insertion to db
I get around that by deleting the rows with condition but is consuming time
this is my code
<?php
include("db.php");
include("header.php");
if (isset($_POST['invoice_btn'])) {
$userId = $_POST['userId'];
$invoice_to = $_POST['companyName'];
$subTotal = $_POST['subTotal'];
$taxAmount = $_POST['taxAmount'];
$taxRate = $_POST['taxRate'];
$totalAftertax = $_POST['totalAftertax'];
$amountPaid = $_POST['amountPaid'];
$amountDue = $_POST['amountDue'];
$notes = $_POST['notes'];
$productCode = $_POST['productCode'];
$productName = $_POST['productName'];
$quantity = $_POST['quantity'];
$price = $_POST['price'];
$total = $_POST['total'];
$dateTime = $_POST['dateTime'];
$submitbutton = $_POST['invoice_btn'];
if ($submitbutton) {
if (empty($productCode)) {
die(" Product code empty ");
} else {
$sqlInsert = "INSERT INTO invoice_order (invoice_to,order_date, order_total_before_tax, order_total_tax, order_tax_per, order_total_after_tax, order_amount_paid, order_total_amount_due, notes)
VALUES ('$invoice_to' ,'$dateTime', '$subTotal', '$taxAmount','$taxRate', '$totalAftertax','$amountPaid', '$amountDue','$notes')";
$result = mysqli_query($conn, $sqlInsert);
// The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.
$lastInsertId = mysqli_insert_id($conn);
foreach ($productCode as $index => $productCodes) {
$s_productCode = $productCodes;
$s_productName = $productName[$index];
$s_quantity = $quantity[$index];
$s_price = $price[$index];
$s_total = $total[$index];
$sqlInsertItem = "INSERT INTO invoice_order_item (order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount)
VALUES ( '$lastInsertId' , '$s_productCode' , '$s_productName' , '$s_quantity', '$s_price', '$s_total')";
$result2 = mysqli_query($conn, $sqlInsertItem);
// Update Quantity on Hand from Produc table
$sqlUpdateQty = "UPDATE product SET pro_quantity = pro_quantity-$s_quantity WHERE pro_id = $s_productCode ";
$result3 = mysqli_query($conn, $sqlUpdateQty);
//delete extra rows that are empty .
$sqlDelete = "DELETE FROM `invoice_order_item` WHERE `item_code`=''";
$Delresult = mysqli_query($conn, $sqlDelete);
} // end foreach
}; // end else
} // end if
In your foreach loop, add a condition before the insertion:
if (empty($s_productCode)) continue;
If the condition becomes true, continue will make the parser skip the rest of the code in the loop.
I am trying to sum (add the values) from the database. My application checks the values from each row, adds up the value from each row up to 2000. And once it reaches up to 2000, it saves in the database (insert query) and continues the same till last record fetched. The total value summed (or totaled) up by each rows should not exceed over 2000.
There are two insert queries, One for inserting the total( from each row between 1800 and 2000) with the ID (like Primary key) generated and the second table add each row inserted with ID (the ID generated becomes now foreign key)
Please refer to the screenshot.
Please find the code below:
$i = 1;
do {
$id = $row_FetchRecordRS['ID'];
$dateissued = $row_FetchRecordRS['DateIssued'];
$rundateCarrierRun = $row_FetchRecordRS['RundateCarrierRunID'];
$timegenerated = $row_FetchRecordRS['TimeGenerated'];
$carrierID = $row_FetchRecordRS['CarrierRunID'] ;
$areaID = $row_FetchRecordRS['CarrierAreaID'];
$address = $row_FetchRecordRS['DeliveryAddress'];
$potzone = $row_FetchRecordRS['Postzone'];
$carr_ID = $row_FetchRecordRS['CarrierID'];
$instruction = $row_FetchRecordRS['DeliveryAddress'];
$areaRep = $row_FetchRecordRS['AreaRepDetails'];
// $vendor = $row_FetchRecordRS['VendorDetails'];
$quantity = $row_FetchRecordRS['Quantity'];
$direct = $row_FetchRecordRS['Direct'];
$jobID = $row_FetchRecordRS['JobID'];
$jobName = $row_FetchRecordRS['JobName'];
$bundlesize = $row_FetchRecordRS['Bundlesize'];
$bundle = $row_FetchRecordRS['Bundles'];
$items = $row_FetchRecordRS['Items'];
$weight = $row_FetchRecordRS['WeightKgs'];
$totalWeightCol = $row_FetchRecordRS['TotalWeightKgs'];
$date = date("D M d, Y G:i");
$total_weight = $row_FetchRecordRS['FinalWeight'] + $total_weight ;
echo "Row: " .$row_FetchRecordRS['FinalWeight']. "<br>";
echo "Total is______ $i : $total_weight <br><br>";
$sqlquerytest = "INSERT INTO `GenerateRun`
(`DateIssued`, `RundateCarrierRunID`, `TimeGenerated`,
`CarrierRunID`, `CarrierAreaID`, `DeliveryAddress`, `Postzone`,
`CarrierID`, `DeliveryInstruction`, `AreaRepDetails`,
`Quantity`, `Direct`, `JobID`, `JobName`, `Bundlesize`,
`Bundles`, `Items`, `WeightKgs`, `TotalWeightKgs`,
`LodingZoneID`)
VALUES
('$dateissued', '$rundateCarrierRun', '$timegenerated',
'$carrierID', '$areaID', '$address', '$potzone', '$carr_ID',
'$instruction', '$areaRep', '$quantity', '$direct', '$jobID',
'$jobName', '$bundlesize', '$bundle', '$items', '$weight',
'$totalWeightCol','$i')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB) or die(mysql_error());
if ($total_weight >= 1800) {
$sqltransitlist = " INSERT INTO `TransitList`(`genID`, `total`) Values ('$i','$total_weight')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB) or die(mysql_error());
$i = $i+1;
$total_weight = 0;
}
} while($row_FetchRecordRS = mysql_fetch_assoc($FetchRecordRS));
Some of your line of codes are irrelevant to your problem. I will simplify it for you.
$i = 1;
$total = 0;
$arr = array(); // for storing a list of data provides that the total doesn't exceed 2000
while ($row = mysql_fetch_assoc($record)) {
$id = $row['id'];
$name = $row['name'];
$num = $row['num'];
$arr[] = array('id' => $id, 'name' => $name, 'num' => $num);
if ($num + $total > 2000) {
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
$arr = array(); // empty the array as the data has been stored to database
$i++;
$total = 0;
} else { // if the total doesn't exceed 2000, add it to total
$total += $num;
}
}
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
Note: this code is just a sample, not your actual code. You can implement my code and match it to your code.
i have a code here that
if the $cost <= $row2['cost_disbursed'], it will execute the if statement here
but, it still deducts the values even if it is less than the value
while ( ($row = mysqli_fetch_array($query_result)) && ($row2 =
mysqli_fetch_array($query_result2)) ) {
if ( $cost <= $row2['cost_disbursed'] ) {
if ($cost <= $row['remaining']){
$sql= "UPDATE project set cost_disbursed = cost_disbursed - '$cost'
WHERE id = '$id'";
$result = mysqli_query($con,$sql);
$sql2= "UPDATE budget set remaining = remaining - '$cost' where id='1'";
$result2 = mysqli_query($con,$sql2);
echo "<script>window.alert('Balance successfully deducted!')
location.href = 'disbursed-Page.php'</script>";
}
}
else {
echo "<script>window.alert('Balance is not enough')
location.href = 'disbursed-Page.php'</script>";
}
}
I have problem with SQL DELETE in PHP language. I don't know where is the problem about delete sql operation.
Could you help me, please?
The code is:
$query = mysqli_query($connessione, "SELECT * FROM (SELECT date, time, temperature FROM streamcopy WHERE moteid = '".$sensor."' AND CONCAT(DATE, ' ',TIME) BETWEEN '".$i."' AND '".$f."' ORDER BY date DESC, time DESC) AS tab ORDER BY date, time");
$n = 0;
$m = 0;
while($row = mysqli_fetch_array($query)){
if($n == 0){
$num = $row['temperature']; //OK
$n = $n+1;
}
else{
$temp[$m] = $row; //OK
if(abs($num - $temp[$m]['temperature'])<0.5){ //OK
$queryFIXED = mysqli_query($connessione, "DELETE FROM streamcopy WHERE moteid = '".$sensor."' AND temperature = '".$temp[$m]['temperature']."' AND date = '".$temp[$m]['date']."' AND time = '".$temp[$m]['time']."')"); /* elimina dati di temperatura k vicini */
$n = $n+1;
$m = $m+1;
}
else{
$num = $temp[$m]['temperature'];
$n = $n+1;
$m = $m+1;
}
}
}
Okay so I am new to PHP and attempting to make a script that takes all of the data from a mysql database I have of stock prices and then looks to see if there was an increase in the stock price during after hours trading (by comparing one day's close price with the next day's open price). I have set up a few scripts like this that work, but for some reason this script isn't copying the data into my sql database and I am completely stumped as to why it won't.When I set up echo statements throughout I discovered that my code is seemingly being executed everywhere but the data isn't transferring. Any help is greatly appreciated.
<?php
include("../includes/connect.php");
function masterLoop(){
$mainTickerFile = fopen("../tickerMaster.txt","r");
while (!feof($mainTickerFile)){
$companyTicker = fgets($mainTickerFile);
$companyTicker = trim($companyTicker);
$nextDayIncrease = 0;
$nextDayDecrease = 0;
$nextDayNoChange = 0;
$total = 0;
$overnight_change = 0;
$overnight_change_pct = 0;
$sumOfIncreases = 0;
$sumOfDecreases = 0;
$sql = "SELECT date, open, close, percent_change FROM $companyTicker";
$result = mysql_query($sql);
if($result){
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$percent_change = $row['percent_change'];
$open = $row['open'];
$close = $row['close'];
$sql2 = "SELECT date, open, close, percent_change FROM $companyTicker WHERE date > '$date' ORDER BY date ASC LIMIT 1";
$result2 = mysql_query($sql2);
$numberOfRows = mysql_num_rows($result2);
if($numberOfRows==1){
$row2 = mysql_fetch_row($result2);
$tom_date= $row2[0];
$tom_open= $row2[1];
$tom_close= $row2[2];
$tom_percent_change= $row2[3];
if ($close == 0){
$close = $tom_open;
}
$overnight_change = $tom_open - $close;
$overnight_change_pct = ($overnight_change/$close)*100;
if($overnight_change_pct > 0){
$nextDayIncrease++;
$sumOfIncreases += $tom_percent_change;
$total++;
}else if($overnight_change_pct < 0){
$nextDayDecrease++;
$sumOfDecreases += $tom_percent_change;
$total++;
}else{
$nextDayNoChange++;
$total++;
}
}else if ($numberOfRows==0){
$total = 1;
$nextDayIncrease = 1;
$nextDayDecrease = 1;
}else{
echo "You have an error in analysis_c3";
}
}
}else{
echo "unable to select $companyTicker <br />";
}
$nextDayIncreasePercent = ($nextDayIncrease/$total) * 100;
$nextDayDecreasePercent = ($nextDayDecrease/$total) * 100;
$averageIncreasePercentage = $sumOfIncreases/$nextDayIncrease;
$averageDecreasePercentage = $sumOfDecreases/$nextDayDecrease;
insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage);
}
}
function insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage){
$buyValue = $nextDayIncreasePercent * $averageIncreasePercentage;
$sellValue = $nextDayDecreasePercent * $averageDecreasePercentage;
$trueValue = $buyValue + $sellValue;
$query="SELECT * FROM analysisOvernightGain5 WHERE ticker='$companyTicker' ";
$result=mysql_query($query);
$numberOfRows = mysql_num_rows($result);
if($numberOfRows==1){
$sql = "UPDATE analysisOvernightGain5 SET ticker='$companyTicker',daysInc='$nextDayIncrease',pctOfDaysInc='$nextDayIncreasePercent',avgIncPct='$averageIncreasePercentage',daysDec='$nextDayDecrease',pctOfDaysDec='$nextDayDecreasePercent',avgDecPct='$averageDecreasePercentage',buyValue='$buyValue',sellValue='$sellValue'trueValue='$trueValue' WHERE ticker='$companyTicker' ";
mysql_query($sql);
}else{
$sql="INSERT INTO analysisOvernightGain5 (ticker,daysInc,pctOfDaysInc,avgIncPct,daysDec,pctOfDaysDec,avgDecPct,buyValue,sellValue,trueValue) VALUES ('$companyTicker', '$nextDayIncrease', '$nextDayIncreasePercent', '$averageIncreasePercentage', '$nextDayDecrease', '$nextDayDecreasePercent', '$averageDecreasePercentage', '$buyValue', '$sellValue','$trueValue')";
mysql_query($sql);
}
}
masterLoop();
?>
you have missed , at ,sellValue='$sellValue'trueValue='$trueValue'
it should be ,sellValue='$sellValue',trueValue='$trueValue'