/** * format a monetary string * * Format a monetary string basing on the amount provided, * ISO currency code provided and a format string consisting of: * * %a - the formatted amount * %C - the currency ISO code (e.g., 'USD') if provided * %c - the currency symbol (e.g., '$') if available * * @param float $amount the monetary amount to display (1234.56) * @param string $currency the three-letter ISO currency code ('USD') * @param string $format the desired currency format * * @return string formatted monetary string * * @static */ static function format($amount, $currency = null, $format = null) { if (CRM_Utils_System::isNull($amount)) { return ''; } $config =& CRM_Core_Config::singleton(); if (!self::$_currencySymbols) { require_once "CRM/Core/PseudoConstant.php"; $currencySymbolName = CRM_Core_PseudoConstant::currencySymbols('name'); $currencySymbol = CRM_Core_PseudoConstant::currencySymbols(); self::$_currencySymbols = array_combine($currencySymbolName, $currencySymbol); } if (!$currency) { $currency = $config->defaultCurrency; } if (!$format) { $format = $config->moneyformat; } // money_format() exists only in certain PHP install (CRM-650) if (is_numeric($amount) and function_exists('money_format')) { $amount = money_format($config->moneyvalueformat, $amount); } $replacements = array('%a' => $amount, '%C' => $currency, '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency)); return strtr($format, $replacements); }
/** * @see Site::show() */ public function showContent() { $artArray = array(); foreach ( $this->digitalArtIterator as $digitalArt ) { $artName = $digitalArt->getDigitalArtName(); $artItem = '<dl>'; $artItem .= '<dt>' . $artName . '</dt>'; $artItem .= sprintf( '<dd><img alt="%s" src="%s" width="100" height="100" /></dd>', $artName, $digitalArt->getDigitalArtMedia() ); $artItem .= '<dd class="by-price"><span class="by">by ' . $digitalArt->getAuthor()->getAuthorName() . '</span>'; $artItem .= '<span class="price">R$ ' . money_format( '%.02n' , $digitalArt->getDigitalArtPrice() ) . '</span></dd>'; $artItem .= sprintf( '<dd class="buy"><a class="buy" href="index.php?action=buy&idDigitalArt=%d">Comprar</a></dd>', $digitalArt->getIdDigitalArt() ); $artItem .= '</dl>'; $artArray[] = $artItem; } if ( count( $artArray ) > 0 ) { $content = sprintf( '<ul><li>%s</li></ul>' , implode( '</li><li>' , $artArray ) ); } else { $content = '<strong>Nenhuma arte encontrada</strong>'; } echo '<h2>Arte Digital</h2>' , $content; }
public static function my_money_format($number) { if (function_exists('money_format')) { return money_format("%i", $number); } return $number; }
function smarty_modifier_money_format($num, $format = "%n", $locale = null) { $curr = false; $savelocale = null; $savelocale = setlocale(LC_MONETARY, null); // use en_US if current locale is unrecognized if ((!isset($locale) || $locale == '') && ($savelocale == '' || $savelocale == 'C')) { $locale = 'en_US'; } if (isset($locale) && $locale != '') { setlocale(LC_MONETARY, $locale); } if (function_exists('money_format')) { $curr = money_format($format, $num); } else { // function would be available in PHP 4.3 //return $num . ' (money_format would be available in PHP 4.3)'; //if not PHP 4.3 , using number format $curr = number_format($num, 0, '.', ','); } if (isset($locale) && $locale != '') { setlocale(LC_MONETARY, $savelocale); } $curr = trim($curr); return $curr; }
/** * @param Product $product * @param integer $qtd */ public function __construct(Product $product, $qtd) { parent::__construct(); $resourceBundle = Application::getInstance()->getBundle(); $idProduct = $product->getIdProduct(); $moneyformat = $resourceBundle->getString('MONEY_FORMAT'); $productName = $product->getProductName(); $productDescription = $product->getProductDescription(); $productPrice = $product->getProductPrice(); $form = $this->addChild(new Form('/?c=cart&a=change&p=' . $idProduct)); //Imagem do produto $form->addChild(new Image($product->getProductImage(), $productName))->setTitle($productName)->setAttribute('width', 80)->setAttribute('height', 80); //Nome e descrição do produto $form->addChild(new Span())->addStyle('name')->addChild(new Text($productName)); $form->addChild(new Span())->addStyle('desc')->addChild(new Text($productDescription)); //Input com a quantidade de itens $form->addChild(new Label(new Text($resourceBundle->getString('QUANTITY'))))->addChild(new Input('qtd'))->setValue($qtd); //Preço unitário $form->addChild(new Span())->addStyle('price')->addChild(new Text(money_format($moneyformat, $productPrice))); //Preço total $form->addChild(new Span())->addStyle('total')->addChild(new Text(money_format($moneyformat, $qtd * $productPrice))); //Botões para edição e exclusão do item do carrinho $form->addChild(new Input('save', Input::SUBMIT))->setValue($resourceBundle->getString('SAVE')); $form->addChild(new Input('del', Input::SUBMIT))->setValue($resourceBundle->getString('DELETE')); }
/** * format a monetary string * * Format a monetary string basing on the amount provided, * ISO currency code provided and a format string consisting of: * * %a - the formatted amount * %C - the currency ISO code (e.g., 'USD') if provided * %c - the currency symbol (e.g., '$') if available * * @param float $amount the monetary amount to display (1234.56) * @param string $currency the three-letter ISO currency code ('USD') * @param string $format the desired currency format * * @return string formatted monetary string * * @static */ function format($amount, $currency = null, $format = null) { if (CRM_Utils_System::isNull($amount)) { return ''; } if (!$GLOBALS['_CRM_UTILS_MONEY']['currencySymbols']) { $GLOBALS['_CRM_UTILS_MONEY']['currencySymbols'] = array('EUR' => '€', 'GBP' => '£', 'ILS' => '₪', 'JPY' => '¥', 'KRW' => '₩', 'LAK' => '₭', 'MNT' => '₮', 'NGN' => '₦', 'PLN' => 'zł', 'THB' => '฿', 'USD' => '$', 'VND' => '₫'); } if (!$currency) { if (!$GLOBALS['_CRM_UTILS_MONEY']['config']) { $GLOBALS['_CRM_UTILS_MONEY']['config'] =& CRM_Core_Config::singleton(); } $currency = $GLOBALS['_CRM_UTILS_MONEY']['config']->defaultCurrency; } if (!$format) { if (!$GLOBALS['_CRM_UTILS_MONEY']['config']) { $GLOBALS['_CRM_UTILS_MONEY']['config'] =& CRM_Core_Config::singleton(); } $format = $GLOBALS['_CRM_UTILS_MONEY']['config']->moneyformat; } $money = $amount; // this function exists only in certain php install (CRM-650) if (function_exists('money_format')) { $money = money_format('%!i', $amount); } $replacements = array('%a' => $money, '%C' => $currency, '%c' => CRM_Utils_Array::value($currency, $GLOBALS['_CRM_UTILS_MONEY']['currencySymbols'], $currency)); return strtr($format, $replacements); }
/** ============================================================================================================ * Take the money from over there, and put it over here * @param array $merchant CamelCased model name One of the merchant_ models in the DoughKit plugin (without "merchant_") * @param array $transactionDetails An array of transaction details * @return array $response An array of the response! */ function chargeIt($merchant = null, $transactionDetails = array()) { if (!$merchant || empty($transactionDetails)) { return false; } $Merchant = ClassRegistry::init('C7DoughKit.Merchant' . $merchant); $this->transactionDetails = array_merge($this->transactionDetails, $transactionDetails); // Do some cleanup/validation on the $transactionDetails fields $this->transactionDetails['amount_to_charge'] = is_numeric(money_format($this->transactionDetails['amount_to_charge'], 2)) ? money_format($this->transactionDetails['amount_to_charge'], 2) : 0; $this->transactionDetails['card_number'] = preg_replace("/[^0-9 ]/", '', $this->transactionDetails['card_number']); $this->transactionDetails['card_exp_month'] = preg_replace("/[^0-9 ]/", '', $this->transactionDetails['card_exp_month']); $this->transactionDetails['card_exp_year'] = preg_replace("/[^0-9 ]/", '', $this->transactionDetails['card_exp_year']); if ($this->transactionDetails['amount_to_charge'] > 0 && !empty($this->transactionDetails['card_number']) && !empty($this->transactionDetails['card_exp_month']) && !empty($this->transactionDetails['card_exp_year'])) { $response = $Merchant->chargeIt($this->transactionDetails); // Address Verification System Response Code Description $AddressVerificationServiceCode = ClassRegistry::init('C7DoughKit.AddressVerificationServiceCode'); $response['avs_response_description'] = isset($response['avs_response_code']) ? $AddressVerificationServiceCode->getCodeDescription($response['avs_response_code']) : ''; // CVV2 Response Code Description $CardVerificationValueResponseCode = ClassRegistry::init('C7DoughKit.CardVerificationValueResponseCode'); $response['cvv_verification_response_description'] = isset($response['cvv_verification_response_code']) ? $CardVerificationValueResponseCode->getCodeDescription($response['cvv_verification_response_code']) : ''; // die(debug($response)); return $response; } return false; }
public function getMoneyAttribute() { setlocale(LC_MONETARY, "vi_VN"); $money = money_format('%i ', (double) $this->getAttribute('money')); $money = str_replace('VND', ' VND', $money); return $money; }
/** * Process the donation * * @param Request $request * * @return json response */ public function donation(Request $request) { try { $charge = Stripe::charges()->create(['currency' => 'CAD', 'amount' => money_format("%i", $request->amount / 100), 'source' => $request->token]); // TODO: Do this better. } catch (\Cartalyst\Stripe\Exception\BadRequestException $e) { return response()->json(['success' => false]); } catch (\Cartalyst\Stripe\Exception\UnauthorizedException $e) { return response()->json(['success' => false]); } catch (\Cartalyst\Stripe\Exception\InvalidRequestException $e) { return response()->json(['success' => false]); } catch (\Cartalyst\Stripe\Exception\NotFoundException $e) { return response()->json(['success' => false]); } catch (\Cartalyst\Stripe\Exception\CardErrorException $e) { return response()->json(['success' => false]); } catch (\Cartalyst\Stripe\Exception\ServerErrorException $e) { return response()->json(['success' => false]); } if ($request->user()) { $request->user()->donations()->create(['stripe_token' => $charge['id'], 'amount' => $request->amount]); } else { /** * The user is not logged in, so here we are creating an anonymous donation in the database * It is not associated with a user id */ $donation = new Donation(); $donation->email = $request->email; $donation->stripe_token = $charge['id']; $donation->amount = $request->amount; $donation->save(); } return response()->json(['success' => true]); }
function smarty_money_format($params, &$smarty) { if (empty($params['price'])) { $params['price'] = 0; } return money_format('%.2n', $params['price']); }
/** * Apply format to argument * * @param var fmt * @param var argument * @return string */ public function apply($fmt, $argument) { if (!function_exists('money_format')) { throw new FormatException('money_format requires PHP >= 4.3.0'); } return money_format($fmt, $argument); }
public function selectProduct($product) { $productPrice = $this->products[$product]['price']; // What do we display if no money is inserted? if ($this->currentAmount == 0) { if ($this->products[$product]['inventory'] == 0) { $this->display = "SOLD OUT"; } else { $displayAmount = $this->products[$product]['price'] / 100; $this->display = "PRICE " . money_format("%.2n", $displayAmount); } } // Enough money has been inserted for the selected product if ($this->currentAmount >= $productPrice) { if ($this->products[$product]['inventory'] == 0) { $this->display = "SOLD OUT"; } else { $this->display = 'THANK YOU'; $this->productDispensed = true; $this->products[$product]['inventory'] -= 1; foreach ($this->coins as $type => $qty) { $this->bank[$type] += $qty; } $overPayment = $this->currentAmount - $productPrice; } } // Do we owe the customer change? if ($overPayment > 0) { $this->makeChange($overPayment); } }
function PriceTable($cart, $total) { setlocale(LC_MONETARY, 'th_TH'); $this->SetFont('Arial', 'B', 10); $this->SetTextColor(0); $this->SetFillColor(36, 140, 129); $this->SetLineWidth(1); $this->Cell(45, 25, "Quantity", 'LTR', 0, 'C', true); $this->Cell(260, 25, "Item Description", 'LTR', 0, 'C', true); $this->Cell(85, 25, "Price", 'LTR', 0, 'C', true); $this->Cell(85, 25, "Sub-Total", 'LTR', 1, 'C', true); $this->SetFont('Arial', ''); $this->SetFillColor(238); $this->SetLineWidth(0.2); $fill = false; foreach ($cart as $cartItem) { $this->Cell(45, 20, $cartItem['quantity'], 1, 0, 'L', $fill); $this->Cell(260, 20, $cartItem['name'], 1, 0, 'L', $fill); $this->Cell(85, 20, money_format("%i", $cartItem['price']), 1, 0, 'R', $fill); $this->Cell(85, 20, money_format("%i", $cartItem['subtotal']), 1, 1, 'R', $fill); $fill = !$fill; } $this->SetX(305 + 40); $this->Cell(85, 20, "Total", 1); $this->Cell(85, 20, money_format("%i", $total) . ' Baht', 1, 1, 'R'); }
protected function outputPdf() { $assistantsCost = filter_input(INPUT_GET, 'assistantsCost'); $toolsCost = filter_input(INPUT_GET, 'toolsCost'); if (isset($assistantsCost)) { $assistantsCost = str_replace(',', '.', $assistantsCost); $assistantsCost = money_format('%.2n', floatval($assistantsCost)); } if (isset($toolsCost)) { $toolsCost = str_replace(',', '.', $toolsCost); $toolsCost = money_format('%.2n', floatval($toolsCost)); } $otherCosts = []; if (isset($_GET['otherCosts']) && count($_GET['otherCosts'])) { $otherCosts = $_GET['otherCosts']; $otherCosts = array_map(function ($otherCost) { $date = date('d.m.Y', strtotime($otherCost['date'])); $amount = money_format('%.2n', floatval($otherCost['amount'])); return ['amount' => $amount, 'date' => $date, 'recipient' => $otherCost['recipient']]; }, $_GET['otherCosts']); } $data = $this->calculateData(); $today = date('d.m.Y H:i'); $title = "Schbas Statistik ({$today})"; $this->_smarty->assign('data', $data); $this->_smarty->assign('assistantsCost', $assistantsCost); $this->_smarty->assign('toolsCost', $toolsCost); $this->_smarty->assign('otherCosts', $otherCosts); $this->_smarty->assign('title', $title); $pdf = new GeneralPdf($this->_pdo); $html = $this->_smarty->fetch(PATH_SMARTY_TPL . '/pdf/schbas-statistics.pdf.tpl'); $pdf->create($title, $html); $pdf->output(); }
function smarty_function_money_format($params, &$smarty) { if (!isset($params['value'])) { show_error('You must pass a "value" to the {money_format} template function.'); } return money_format("%!^i", $params['value']); }
function immopress_get_fields($args) { global $post, $ImmoPress; // Parse incomming $args into an array and merge it with $defaults extract(wp_parse_args($args, array('id' => $post->ID, 'exclude' => array())), EXTR_SKIP); if (!isset($ImmoPress->fields)) { return false; } $exclude = split(',', $exclude); $fields = $ImmoPress->fields; $arr = array(); $currency_fields = array('price', 'baseRent', 'serviceCharge', 'totalRent'); $square_fields = array('livingSpace', 'usableFloorSpace'); setlocale(LC_MONETARY, 'de_DE'); foreach ($fields as $key => $value) { // Pop fields if (in_array($key, $exclude)) { continue; } $entry = get_post_meta($id, $key, true); if ($entry) { // Use correct currency display. if (in_array($key, $currency_fields)) { $entry = money_format('%.2n', $entry); } // Append unit to square measure if (in_array($key, $square_fields)) { $entry = str_replace('.', ',', $entry) . ' m²'; } $arr[$key] = $entry; } } return $arr; }
/** * @Route("/sheet/calc") */ public function calcAction(Request $request) { $session = $request->getSession(); /* * The first time the page loads during a session * we load the three default tiers. * * Otherwise we get the tiers from the session. * */ if ($session->has('tiers')) { $tiers = $session->get('tiers'); } else { $tiers = new Tiers(); $tiers->setDefaultTiers(); $session->set('tiers', $tiers); } $artifacts = $request->request->get('artifacts', $session->get('artifacts', 0)); $session->set('artifacts', $artifacts); $duplicates = $request->request->get('duplicates', $session->get('duplicates', 0)); $session->set('duplicates', $duplicates); $versions = $request->request->get('versions', $session->get('versions', 0)); $session->set('versions', $versions); $removed = $artifacts * $duplicates / 100; $folded = ($artifacts - $removed) * $versions / 100; $total = $artifacts - $removed - $folded; $tiers->processTiers($total); $totalCost = $tiers->calculateTotalCost(); if ($total > 0) { $average = $totalCost / $total; } else { $average = 0; } return $this->render('sheet/sheet.html.twig', array('artifacts' => $artifacts, 'duplicates' => $duplicates, 'versions' => $versions, 'removed' => $removed, 'folded' => $folded, 'total' => $total, 'totalCost' => money_format('$%i', $totalCost), 'average' => money_format('$%i', $average), 'paCost' => money_format('$%i', $totalCost * 12))); }
/** * display - displays a receipt * * @param \Cilex\Store\Products $products - products to be displayed * @param double $subtotal - subtotal of the transaction * @param double $total - total value of the transaction * @param double $discount - dicount value applied to transaction * @return string */ public static function display(\Cilex\Store\Products $products, $subtotal, $total, $discount = null) { $text = array(); $text[] = PHP_EOL . '----------Receipt ' . gmdate('d-m-Y', time()) . '------------' . PHP_EOL; $text[] = '----------------Products----------------' . PHP_EOL; //products if (!empty($products->getProperties())) { foreach ($products->getProperties() as $product => $value) { $valueFormatted = is_double($value) ? money_format('%.2n', $value) : $value; //set text $text[] = ucwords(str_replace('-', ' ', $product)) . ' [' . $valueFormatted . ']'; } } else { $text[] = 'There are no products to display!'; } //subtotal $subtotalFormatted = is_double($subtotal) ? money_format('%.2n', $subtotal) : $subtotal; $text[] = PHP_EOL . '------------------------' . PHP_EOL; $text[] = 'SubTotal [' . $subtotalFormatted . ']'; //discount $discountFormatted = is_double($discount) ? money_format('%.2n', $discount) : $discount; if ($discount !== null) { $text[] = PHP_EOL . '------------------------' . PHP_EOL; $text[] = 'Discount [' . $discountFormatted . ']'; } //total $totalFormatted = is_double($total) ? money_format('%.2n', $total) : $total; $text[] = PHP_EOL . '------------------------' . PHP_EOL; $text[] = 'Total [' . $totalFormatted . ']' . PHP_EOL; return $text; }
/** * Displays the details of the requested stock. */ public function display() { $this->load->helper('form'); if (!empty($this->input->post('stock'))) { $code = $this->input->post('stock'); $this->data['src'] = "../assets/js/stock-history.js"; } else { $code = $this->uri->segment(3); $this->data['src'] = "../../assets/js/stock-history.js"; } $this->data['title'] = "Stocks ~ {$code}"; $this->data['left-panel-content'] = 'stock/index'; $this->data['right-panel-content'] = 'stock/sales'; $this->data['stock_code'] = $code; $this->data['trans'] = $this->transactions->getSalesTransactions($code); $form = form_open('stock/display'); $stock_codes = array(); $stock_names = array(); $stocks = $this->stocks->getAllStocks(); $stock = $this->stocks->get($code); foreach ($stocks as $item) { array_push($stock_codes, $item->Code); array_push($stock_names, $item->Name); } $stocks = array_combine($stock_codes, $stock_names); $select = form_dropdown('stock', $stocks, $code, "class = 'form-control'" . "onchange = 'this.form.submit()'"); $this->data['Name'] = $stock->Name; $this->data['Code'] = $stock->Code; $this->data['Category'] = $stock->Category; $this->data['Value'] = money_format("\$%i", $stock->Value); $this->data['form'] = $form; $this->data['select'] = $select; $this->render(); }
function display($results, $db) { setlocale(LC_MONETARY, 'en_US'); $outputArray = array(); foreach ($results as $result) { $formattedRec = ""; if ($formattedRec == "") { if ($result["grant_title"] != "") { $formattedRec = html_encode($result["grant_title"]) . ", "; } if ($result["funding_status"] == "funded") { if ($result["amount_received"] != "") { $formattedRec = $formattedRec . money_format('%(#10n', $result["amount_received"]) . ", "; } } else { if ($result["funding_status"] == "submitted") { if ($result["amount_received"] != "") { $formattedRec = $formattedRec . money_format('%(#10n', $result["amount_received"]) . ", "; } } } if ($result["type"] != "") { $formattedRec = $formattedRec . html_encode($result["type"]) . ", "; } if (isset($result["agency"]) && $result["agency"] != "") { $formattedRec = $formattedRec . html_encode($result["agency"]) . ", "; } if (isset($result["start_year"])) { $formattedRec = $formattedRec . html_encode($result['start_month']) . "-" . html_encode($result['start_year']) . " / " . (html_encode($result['end_month']) == 0 ? "N/A" : html_encode($result['end_month']) . "-" . html_encode($result['end_year'])) . ", "; } if ($result["principal_investigator"] != "") { $formattedRec = $formattedRec . html_encode($result["principal_investigator"]); } if ($result["co_investigator_list"] != "") { $formattedRec = $formattedRec . html_encode($result["co_investigator_list"]); } // Check for existance of extra comma or colon at the end of the record // if there is one remove it $lengthOfRec = strlen($formattedRec) - 2; $lastChar = substr($formattedRec, $lengthOfRec, 1); if ($lastChar == "," || $lastChar == ":") { $formattedRec = substr($formattedRec, 0, $lengthOfRec); } } // Do not allow duplicates (i.e. multiple faculty report the same publication. if (in_array($formattedRec, $outputArray) === false) { $outputArray[] = $formattedRec; } } if (count($outputArray) > 0) { for ($u = 0; $u < count($outputArray); $u++) { $ctr = $u + 1; $outputString = $outputArray[$u] . "<br /><br />"; echo $outputString; } } else { echo "No Grants for the specified query.<br>"; } }
protected function _format($value) { if (function_exists('money_format')) { return money_format('%!i', $value); } else { return $value; } }
function currency($number, $symbol = TRUE) { if ($symbol) { return money_format('%.2n', $number); } else { return money_format('%!.2n', $number); } }
/** * executes the command * * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $offers = $this->apiClient->offer()->all(); foreach ($offers as $offer) { $gross = money_format('%=*^-14#8.2i', $offer->getSum()->getGross()); $output->writeln(sprintf('(ID:%s) %s: %s%s', $offer->getId(), $offer->getBase()->getCustomerCompany(), $gross, $offer->getBase()->getCurrencySymbol())); } }
function smarty_modifier_money_format($string, $places = 2) { $env = localeconv(); if ($env['int_curr_symbol'] != 'USD') { setlocale(LC_MONETARY, 'en_US'); } return money_format("%.{$places}n", $string); }
/** * Returns formatted currency number view model * * @return JsonModel */ public function currencyAction() { $value = $this->getRequestValue(); if ($value !== null) { return $this->getView(money_format('%.2n', $this->getRequestValue())); } return $this->getNonNumericView(); }
/** * executes the command * * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $id = $input->getArgument('id'); $output->writeln('Retrieving offer data for id: ' . $id); $offer = $this->apiClient->offer()->get($id); $gross = money_format('%=*^-14#8.2i', $offer->getSum()->getGross()); $output->writeln(sprintf('(ID:%s) %s: %s%s', $offer->getId(), $offer->getBase()->getCustomerCompany(), $gross, $offer->getBase()->getCurrencySymbol())); }
/** * @param string $value * @return string */ public function format($value) { if (function_exists('money_format')) { setlocale(LC_MONETARY, $this->locale); return money_format($this->formatString, $value); } return sprintf('$%1.2f', $value); }
public function getPurchaseCost() { if (!$this->DepreciationFlag) { return null; } else { return money_format('%i', round($this->PurchaseCost, 2)); } }
function format_money($amount, $to_dollars = true) { if ($to_dollars) { $amount = $amount / 100; } $retval = money_format('%(#1n', $amount); return $retval; }
function showCart() { $books = $_COOKIE['books']; if (empty($books)) { $books = array(); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_POST['submit'] == 'Add to Cart') { $isbn = $_POST['isbn']; $quantity = intval($_POST['quantity']); $title = $_POST['title']; if ($quantity == 1) { $copies = "copy"; $have = "have"; } else { $copies = "copies"; $have = "has"; } echo "\n <p class='center'>\n {$quantity} {$copies} of <em><strong>{$title}</strong></em> {$have}\n been added to your shopping cart.\n </p><br>"; if (array_key_exists($isbn, $books)) { $books[$isbn] = strval(intval($books[$isbn]) + $quantity); } else { $books[$isbn] = strval($quantity); } } else { if ($_POST['submit'] == 'Clear Cart') { echo "<p class='center'>Your shopping cart has been cleared.</p>"; $books = array(); } } } echo "\n <form action='place_order.php' method='post'>\n <table>\n <tr>\n <th>ISBN</th>\n <th>Title</th>\n <th>Author</th>\n <th>Publisher</th>\n <th>Price</th>\n <th>Quantity</th>\n <th>Subtotal</th>\n </tr>"; if (count($books) == 0) { echo "\n </table>\n </form>\n <p class='center'>Your shopping cart is empty.</p>"; return; } $n = 0; $num_books = 0; $subtotal = 0; $connection = connect(); foreach ($books as $isbn => $quantity) { $n++; $num_books += $quantity; $subtotal += showOrderedBook($connection, $isbn, $quantity); } $subtotal_string = money_format("%i", $subtotal); echo "</table><br>"; echo "\n <input type='hidden' name='total_price_string' value='{$subtotal_string}'>\n <table>\n <tr>\n <th class='right'>Number of Books</th>\n <td>{$num_books}</td>\n </tr>\n <tr>\n <th class='right'>Total Price</th>\n <td>\${$subtotal_string}</td>\n </tr>\n <tr>\n <th class='right'>Shipping Method</th>\n <td>\n <select name='shipping_method'>\n <option value='ground'>ground</option>\n <option value='express'>express</option>\n </select>\n </td>\n </tr>"; // FIXME: Show payment selection or add payment method button. echo "\n <tr>\n <th class='right'>Payment Method</th>\n <td>\n <select name='card_number'>"; $payments = getPaymentMethods($connection, $_COOKIE['customer_id']); foreach ($payments as $payment) { echo "\n <option value='{$payment['card_number']}'>\n {$payment['display_name']}\n </option>"; } echo "\n </select>\n </td>\n </tr>\n </table>\n <br>\n <input type='submit' class='button' name='submit' value='Place Order'>\n </form>"; echo "\n <form action='show_cart.php' method='post'>\n <br>\n <p class='center'>\n You may also choose to clear the shopping cart and start over.\n </p>\n <input type='submit' class='button' name='submit' value='Clear Cart'>\n </form>"; mysql_close($connection); }