Jump to content

desmond_ckl

Members
  • Posts

    24
  • Joined

  • Last visited

    Never

Everything posted by desmond_ckl

  1. Hi experts ! i need guide line for php post Example: In A.php i done my calculation , i would like to use form action post to C.php but before that i need go through B.php. A.php do calculation then next step is B.php let user enter information final step is C.php show information of A.php + B.php A.php coding example: <form action='C.php' method='POST'> <input .....> <input type="submit" name="Submit" /> </form>
  2. Dear all, i need help so badly...urgent :'( i have customize a simple e-comm site (from www.phpwebcommerce.com tutorial), when user go checkout page(cart.php) it will show product item, quantity, sub-total , shipping, state and total price. Original from the tutorial using php do calculation but shipping cost is flat rate, i need to calculate shipping cost by state & quantity so that i use JavaScript do the calculation. my shopping cart process : 1. user checkout - go to cart.php (user can update qunatity and select state from this page then update cart) this page is working fine... 2. user enter info - user enter payment and shipping address 3. user continue checkout - go to checkoutconfirmation.php (my problem appear here, the information like quantity, sub-total, shipping cost & total from cart.php won't update here) I'm trying not do confuse myself & do it the eaiser way by using PHP cookies to send the javascript value tocheckoutconfirmation.php but i'm not sure how it work....i'm new to php and javascript, any help will appeciated ! Thank you in advanced !! cart.php <?php require_once 'library/config.php'; require_once 'library/cart-functions.php'; $action = (isset($_GET['action']) && $_GET['action'] != '') ? $_GET['action'] : 'view'; switch ($action) { case 'add' : addToCart(); break; case 'update' : updateCart(); break; case 'delete' : deleteFromCart(); break; case 'view' : } $cartContent = getCartContent(); $numItem = count($cartContent); $pageTitle = 'Shopping Cart'; require_once 'include/header.php'; // show the error message ( if we have any ) displayError(); if ($numItem > 0 ) { ?> <head> <script type="text/javascript"> <!-- Begin function doMath() { var one = eval(document.getElementById('txtQty[]').value) //one = quantity //alert(one); var price = 0; var state = document.frmCart.state.value; ///////var pd_price = 72; ////////////// var unitPrice = document.getElementById('pd_price').innerText.substring(3); //alert(unitPrice); //alert(one); if(state == "east"){ if (one == 1){ price = 6; } else if (one == 2){ price = 8; } else if (one == 3){ price = 10; } else if (one == 4){ price = 12; } else if (one == 5){ price = 12.50; } else if (one == 6){ price = 13; } else if (one == 7){ price = 14; } else if (one == { price = 0; } } else if(state == "west"){ if (one == 1){ price = 9.30; } if (one == 2){ price = 12; } if (one == 3){ price = 17.25; } if (one == 4){ price = 20; } if (one == 5){ price = 21; } if (one == 6){ price = 22; } if (one == 7){ price = 23.45; } if (one == { price = 0; } } document.getElementById('subtotal').innerText = "MYR" + unitPrice * one; //document.frmCart.amount.innerText=price; document.getElementById('amount').innerText = price; ///amount = shipping //alert("asdf"); var test = document.getElementById('subtotal').innerText; // = one*pd_price; // //alert(test); //alert(one); test = parseInt(test.substring(3)) * one; //alert(test); //document.getElementById('subtotal').innerText = test; //alert(test); //alert("A" + price); //alert(parseInt(test)); //alert(one); document.getElementById('total').innerText = price + unitPrice * one; //total = shipping + subtotal test = "MYR" + test; document.getElementById('ct_qty').innerText = document.getElementById('subtotal').innerText; } //function custRound(x,places) { //return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places) //} // End -->s </script> </head> <body onLoad="MM_preloadImages('../images/'), doMath()" > <tr><td align="center"><table width="900" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td align="center" bgcolor="#b6df51"><table width="800" border="0" cellspacing="0" cellpadding="0"><tr><td align="center"><table width="900" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td align="center"><table width="900" border="0" align="center" cellpadding="0" cellspacing="0"> <tr><form action="<?php echo $_SERVER['PHP_SELF'] . "?action=update"; ?>" method="post" name="frmCart" id="frmCart"> <td align="center" bgcolor="#b6df51"><table width="800" border="0" cellspacing="0" cellpadding="0" > <tr> <td align="left"><img src="images/title_purchase_online.gif" width="280" height="25" /></td> </tr> <tr> <td> </td> </tr> <tr> <td align="center"><table width="800" border="0" cellspacing="0" cellpadding="0"> <tr> <td><table width="800" border="0" cellpadding="0" cellspacing="0" bgcolor="#3b7b37"> <tr> <td width="15"><img src="images/title_box_left.gif" width="15" height="30" /></td> <td width="770"><table width="770" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="170" align="center" class="yellow_txt"><strong>Item</strong></td> <td width="213" align="center"> </td> <td width="141" align="center"><strong class="yellow_txt">Unit Price</strong></td> <td width="106" align="center"><strong class="yellow_txt">Quantity</strong></td> <td width="110" align="center"><strong class="yellow_txt">Total</strong></td> <td width="30" align="center"> </td> </tr> </table></td> <td width="15"><img src="images/title_box_right.gif" width="15" height="30" /></td> </tr> </table></td> </tr> <?php $subTotal = 0; for ($i = 0; $i < $numItem; $i++) { extract($cartContent[$i]); $productUrl = "other_products.php?c=$cat_id&p=$pd_id"; $subTotal += $pd_price * $ct_qty; ?> <tr> <td> </td> </tr> <tr> <td align="center"><table width="770" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="170" align="center" class="yellow_txt"><table width="150" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> </tr> <tr> <td width="116" align="center" valign="top" bgcolor="#b6df51"><a href="<?php echo $productUrl; ?>"><img src="<?php echo $pd_thumbnail; ?>" width="116" height="116" border="0" /></a><a href="<?php echo $productUrl; ?>"></a></td> </tr> <tr> </tr> </table></td> <td width="220" align="left" class="green_txt"><strong><a href="<?php echo $productUrl; ?>" style="text-decoration: none"><font color="000000"><?php echo $pd_name; ?></font></a></strong></td> <td width="128" align="center"><strong class="black_txt" id="pd_price"><?php echo displayAmount($pd_price); ?></strong></td> <td width="112" align="center"><input name="txtQty[]" type="text" id="txtQty[]" size="5" value="<?php echo $ct_qty; ?>" class="box" onKeyUp="checkNumber(this);"> <input name="hidCartId[]" type="hidden" value="<?php echo $ct_id; ?>"> <input name="hidProductId[]" type="hidden" value="<?php echo $pd_id; ?>"></td> <td width="110" align="center"><strong class="black_txt" id="ct_qty"><?php echo displayAmount($pd_price * $ct_qty); ?></strong></td> <td width="30" align="center" valign="middle"><a href="#"> <img src="images/btn_delete.png" width="16" height="16" border="0" onClick="window.location.href='<?php echo $_SERVER['PHP_SELF'] . "?action=delete&cid=$ct_id"; ?>';" /></a> </tr> </table></td> </tr> <?php } ?> <tr> <td> </td> </tr> <tr> <td><table width="800" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="13" height="13"><img src="images/text_box_big_left1.gif" width="13" height="13" /></td> <td width="774" height="13" bgcolor="#ffde00"><span class="style10"><img src="images/spacer.gif" width="13" height="13" /></span></td> <td width="13" height="13"><img src="images/text_box_big_right1.gif" width="13" height="13" /></td> </tr> <tr> <td bgcolor="#ffde00"> </td> <td height="50" align="center" bgcolor="#ffde00"><table width="770" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="132" align="center" class="yellow_txt"> </td> <td width="147" align="left" class="green_txt"> </td> <td width="113" align="center"> </td> <td width="102" align="center" class="black_txt"><strong>Sub-total</strong></td> <td colspan="2" align="center"><strong class="black_txt" id="subtotal"><?php echo displayAmount($subTotal); ?></strong></td> <td width="19" align="center" valign="middle"> </td> </tr> <tr> <td colspan="7" align="center" class="yellow_txt"><img src="images/spacer.gif" width="10" height="10" /></td> </tr> <!-------------------------------------------- shipping cost---------------------------------------------------> <tr> <td align="center" > </td> <td align="left" class="green_txt"> </td> <td> </td> <td align="center" class="black_txt"><strong>State</strong></td> <td colspan="2" align="center"> <select name="state"> <option value="east" selected>East </option> <option value="west">Peninsular</option> </select> </td> <td align="center" valign="middle"> </td> </tr> <tr> <td colspan="7" align="center" class="yellow_txt"><img src="images/spacer.gif" width="10" height="10" /></td> </tr> <tr> <td align="center" class="yellow_txt"> </td> <td align="left" class="green_txt"> </td> <td align="center"> </td> <td align="center" class="black_txt"><strong>Shipping</strong></td> <td width="131" align="right"> <strong class="black_txt"> MYR</strong><!--<input type="text" name="amount" disabled="disabled" size="17" style="background-color:transparent;" border="none" >--></td> <td width="122" align="left"><strong class="black_txt"> <div name="amount" id="amount"> 0</div></strong></td> <td align="center" valign="middle"> </td> </tr> <tr> <td align="center" class="yellow_txt"> </td> <td align="left" class="green_txt"> </td> <td align="center"> </td> <td align="center" class="black_txt33"> </td> <td colspan="2" align="center" class="black_txt33"> <font color="#FF0000">*Purchases of 8 boxes onwards free delivery charges.</font> </td> <td align="center" valign="middle"> </td> </tr> <!------------------------------------------------------------------------------------------------------> <tr> <td colspan="7" align="center" class="yellow_txt"><img src="images/spacer.gif" width="10" height="10" /></td> </tr> <tr> <td align="center" class="yellow_txt"> </td> <td align="left" class="green_txt"> </td> <td align="center"> </td> <td align="center" class="black_txt"><strong>Total</strong></td> <td width="131" align="right"> <!--<input type="text" name="amount" disabled="disabled" size="17" style="background-color:transparent;" border="none" >--><strong class="black_txt"> MYR</strong></td> <td colspan="2" align="left"><strong class="black_txt" id="total"><?php echo displayAmount($subTotal);// + $shopConfig['shippingCost']); ?></strong> </td> <td width="4" align="center" valign="middle"> </td> </tr> <tr> <td colspan="7" align="center" class="yellow_txt"><img src="images/spacer.gif" width="10" height="10" /></td> </tr> <tr> <td align="center" class="yellow_txt"> </td> <td align="left" class="green_txt"> </td> <td align="center"> </td> <td align="center"> </td> <td colspan="2" align="center"><input type="button" class="update_btn" src="images/btn_update_cart.gif" width="102" height="22" border="0" name="btnUpdate" id="btnUpdate" onClick="doMath()"><!--value="submit"--></td> <td align="center" valign="middle"> </td> </tr> </table></td> <td bgcolor="#ffde00"> </td> </tr> <tr> <td width="13" height="13"><img src="images/text_box_big_left2.gif" width="13" height="13" /></td> <td bgcolor="#ffde00"><span class="style10"><img src="images/spacer.gif" width="13" height="13" /></span></td> <td width="13" height="13"><img src="images/text_box_big_right2.gif" width="13" height="13" /></td> </tr> <tr> <td> </td> </tr> </table></td> </tr> <tr> <?php $shoppingReturnUrl = isset($_SESSION['shop_return_url']) ? $_SESSION['shop_return_url'] : 'other_products.php'; ?> <tr> <td align="center"><table width="340" border="0" cellspacing="0" cellpadding="0"> <tr> <td> </td> <td><a href="#"> <img src="images/btn_continue_shopping.gif" width="162" height="22" border="0" onClick="window.location.href='<?php echo $shoppingReturnUrl; ?>';" /></a></td> <?php if ($numItem > 0) { ?> <td width="20"> </td> <td><a href="#"> <img src="images/btn_continue_checkout.gif" width="162" height="22" border="0" onClick="window.location.href='checkout.php?step=1';"/></a></td> <?php } ?> </tr> </table></td> </tr> </table></td> </tr> <tr> <td align="center"> </td> </tr> </table></td></form> </tr> </table></td> </tr> </table> </tr> </table></td> </tr> </table></td> </tr> <?php } else { ?> <?php include("EmptyMSG.php"); ?> <!----<td><table width="550" bgcolor="#b6df51" border="0" align="center" cellpadding="10" cellspacing="0"><p align="center">You shopping cart is empty</p> <p>If you find you are unable to add anything to your cart, please ensure that your internet browser has cookies enabled and that any other security software is not blocking your shopping session.</p> </table></td>---> <?php } ?> </body> </html> checkoutConfirmation.php <?php /* Line 1 : Make sure this file is included instead of requested directly Line 2 : Check if step is defined and the value is two Line 3 : The POST request must come from this page but the value of step is one */ if (!defined('WEB_ROOT') || !isset($_GET['step']) || (int)$_GET['step'] != 2 || $_SERVER['HTTP_REFERER'] != 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?step=1') { exit; } $errorMessage = ' '; /* Make sure all the required field exist is $_POST and the value is not empty Note: txtShippingAddress2 and txtPaymentAddress2 are optional */ $requiredField = array('txtShippingFirstName', 'txtShippingLastName', 'txtShippingAddress1', 'txtShippingPhone', 'txtShippingState', 'txtShippingCity', 'txtShippingPostalCode', 'txtPaymentFirstName', 'txtPaymentLastName', 'txtPaymentAddress1', 'txtPaymentPhone', 'txtPaymentState', 'txtPaymentCity', 'txtPaymentPostalCode'); if (!checkRequiredPost($requiredField)) { $errorMessage = 'Input not complete'; } $cartContent = getCartContent(); ?> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"> </td> </tr> </table> </td> </tr> </table></td> </tr> <form action="<?php echo $_SERVER['PHP_SELF']; ?>?step=3" method="post" name="frmCheckout" id="frmCheckout"> <table width="900" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td align="center" bgcolor="#b6df51"><table width="800" border="0" cellspacing="0" cellpadding="0"><tr><td align="center"><table width="900" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> </tr> <tr> <td align="center"><table width="900" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td align="center" bgcolor="#b6df51"> <!------------------------------COD-------------------------------------> <?php if ($_POST['optPayment'] == 'cod') { ?> <table width="800" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="330" align="left"><img src="images/title_purchase_online.gif" width="280" height="25" /></td> <td width="464" align="left" valign="bottom"><img src="images/title_step02.gif" width="245" height="20" /></td> </tr> <tr> <td colspan="2"> </td> <p id="errorMessage"><?php echo $errorMessage; ?></p> </tr> <tr> <td colspan="2" align="center" class="green_txt"><table width="500" border="0" cellpadding="0" cellspacing="0" bgcolor="#3b7b37"> <tr> <td width="15"><img src="images/title_box_left.gif" width="15" height="30" /></td> <td width="470" align="center" class="yellow_txt"><strong>:: IMPORTANT NOTE ::</strong></td> <td width="15"><img src="images/title_box_right.gif" width="15" height="30" /></td> </tr> </table></td> </tr> <tr> <td colspan="2" align="center"><img src="images/spacer.gif" width="12" height="12" /></td> </tr> <tr> <td colspan="2" align="center"> </td> <p id="errorMessage"><?php echo $errorMessage; ?></p> </tr> <?php } ?> <!-----------------paypal---------------------------------> <?php if ($_POST['optPayment'] == 'paypal') { ?> <tr> <td colspan="2" align="center"><table width="800" border="0" align="center" cellpadding="10" cellspacing="1" class="infoTable"><tr><td><table width="800" border="0" align="center" cellpadding="10" cellspacing="1" class="infoTable"> <tr> <tr> <td width="330" align="left"><img src="images/title_purchase_online.gif" width="280" height="25" /></td> <td width="464" align="left" valign="bottom"><img src="images/title_step02.gif" width="245" height="20" /></td> </tr> <td colspan="2" align="center" class="green_txt"><table width="500" border="0" cellpadding="0" cellspacing="0" bgcolor="#3b7b37"> <tr> <td width="15"><img src="images/title_box_left.gif" width="15" height="30" /></td> <td width="470" align="center" class="yellow_txt"><strong>:: IMPORTANT NOTE ::</strong></td> <td width="15"><img src="images/title_box_right.gif" width="15" height="30" /></td> </tr> </table></td> </tr> <td colspan="2" align="center" ><table width="500" border="0" cellpadding="0" cellspacing="0" > <tr> <td align="center" class="black_txt33"><p>There will be (3.4% + RM2.00 MYR) PayPal transaction fee for credit card payment</p></td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> <?php } ?> <!-----------------End of paypal----------------------------> <tr> <td colspan="2" align="center"><table width="500" border="0" cellpadding="0" cellspacing="0" bgcolor="#3b7b37"> <tr> <td width="15"><img src="images/title_box_left.gif" width="15" height="30" /></td> <td width="470" align="center" class="yellow_txt"><strong>Ordered Item</strong></td> <td width="15"><img src="images/title_box_right.gif" width="15" height="30" /></td> </tr> </table></td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> <tr> <td colspan="2" align="center"><table width="360" border="0" cellspacing="0" cellpadding="3"> <tr> <td align="left" class="green_txt"><strong>Item</strong></td> <td align="right" class="green_txt"><strong>Unit Price</strong></td> <td align="right" class="green_txt"><strong>Total</strong></td> </tr> <?php $numItem = count($cartContent); $subTotal = 0; for ($i = 0; $i < $numItem; $i++) { extract($cartContent[$i]); $subTotal += $pd_price * $ct_qty; ?> <tr> <td align="left" class="black_txt"><?php echo "$ct_qty x $pd_name"; ?></td> <td align="right" class="black_txt"><?php echo displayAmount($pd_price); ?></td> <td align="right" class="black_txt"><?php echo displayAmount($ct_qty * $pd_price); ?></td> </tr> <?php } ?> <tr> <td colspan="3" align="left"><img src="images/spacer.gif" width="12" height="12" /></td> </tr> <tr> <td align="left"> </td> <td align="right" class="green_txt"><strong>Sub-totall</strong></td> <td align="right"><span class="black_txt"><?php echo displayAmount($subTotal); ?></span></td> </tr> <tr> <td align="left"> </td> <td align="right" class="green_txt"><strong>Shipping<br /> </strong></td> <td align="right"><span class="black_txt"><?php echo displayAmount($shopConfig['shippingCost']); ?></span></td> </tr> <tr> <td align="left"> </td> <td align="right" class="green_txt"><strong>Total</strong></td> <td align="right"><span class="black_txt"><?php echo displayAmount($shopConfig['shippingCost'] + $subTotal); ?></span></td> </tr> </table></td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> <tr> <td colspan="2" align="center" class="black_txt"><strong><?php echo $_POST['optPayment'] == 'paypal' ? 'Paypal' : 'Bank-in / Bank Transfer'; ?> <input name="hidPaymentMethod" type="hidden" id="hidPaymentMethod" value="<?php echo $_POST['optPayment']; ?>" /></strong></td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> <tr> <td colspan="2" align="center"><table width="380" border="0" cellspacing="0" cellpadding="0"> <tr> <td ><input name="btnBack" type="button" id="btnBack" onClick="window.location.href='checkout.php?step=1';" class="btn" ></td> <td width="20"> </td> <td><input type="image" src="images/btn_confirm_order.gif" width="132" height="22" border="0" value="Submit" name="btnConfirm" id="btnConfirm"></td> </tr> </table></td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> </table></td> </tr> </table></td> </tr> </table> <table width="800" border="0" cellspacing="0" cellpadding="0"><tr></tr> </table></td> </tr> </table></td> </tr> </table></td> </tr> </form> </body> </html> thank you for the time and attention
  3. 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; } ?>
  4. Hi there, I'm new to PHP about 5month (previously i don't have any programming background), i study the basic PHP through online. i found a tutorial from : http://www.phpwebcommerce.com/ , and there is some error in this tutorial + i need customize this tutorial for my site. I'm here to ask , is the tutorial suitable beginner like me ? is the tutorial consider for advanced used ? i able to solve some error in this tutorial but it take too long. Can give a solution ? should i give up this tutorial on my site ? or just continue find solution ? but i'm already spent almost 2month in this tutorial. so far, i left shipping cost cant find solution...(but i have try do it for 2weeks) Thank you.
  5. Hi there, I would like to customize $shippingCost in my shopping cart. I follow a tutorial from: http://www.phpwebcommerce.com/plaincart/index.php This tutorial using flat shipping rate, how to customize shippingCost based on the product weight ? Example: shipping method will based on weight & place within Malaysia: west malaysia, up to 1kg = rm9 east malaysia, up to 1kg = rm12 west malaysia, up to 2kg = rm12 east malaysia, up to 2kg = rm16 west malaysia, up to 5kg = rm18 east malaysia, up to 5kg = rm32 west malaysia, up to 10kg = rm24 east malaysia, up to 10kg = rm48 Do i need to create a new field inside my database for product weight ? is it $weight * $product_quantity ? Does anyone know how to accomplish this customization? . Please help because I am very confuse. Thank you in advanced 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; $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; } ?> any help will be greatly appreciated
  6. Hi there, I would like to customize $shippingCost in my shopping cart. I follow a tutorial from: http://www.phpwebcommerce.com/plaincart/index.php This tutorial using flat shipping rate, how to customize shippingCost based on the product weight ? Example: shipping method will based on weight & place within Malaysia: west malaysia, up to 1kg = rm9 east malaysia, up to 1kg = rm12 west malaysia, up to 2kg = rm12 east malaysia, up to 2kg = rm16 west malaysia, up to 5kg = rm18 east malaysia, up to 5kg = rm32 west malaysia, up to 10kg = rm24 east malaysia, up to 10kg = rm48 Do i need to create a new field inside my database for product weight ? is it $weight * $product_quantity ? Does anyone know how to accomplish this customization? . Please help because I am very confuse. Thank you in advanced 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; $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; } ?> any help will be greatly appreciated
  7. I would like to customize my product-list page to display all my products in a grid with an ADD TO CART option for each product. That means i have two ADD TO CART button on the site, in productDetail.php there is a ADD TO CART button original from the tutorial, i need customize another ADD TO CART button on productList.php. Does anyone know how to accomplish this customization? . Please help because I am stuck with the coding for 3weeks :'( :'( Tutorial site: http://www.phpwebcommerce.com/plaincart/index.php productDetail.php: <?php if (!defined('WEB_ROOT')) { exit; } $product = getProductDetail($pdId, $catId); // we have $pd_name, $pd_price, $pd_description, $pd_image, $cart_url extract($product); ?> <table width="100%" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center"><img src="<?php echo $pd_image; ?>" border="0" alt="<?php echo $pd_name; ?>" width="230" height="170"></td> <td valign="middle"> <strong><?php echo $pd_name; ?></strong><br> Price : <?php echo displayAmount($pd_price); ?><br> <?php // if we still have this product in stock // show the 'Add to cart' button if ($pd_qty > 0) { ?> <input type="button" name="btnAddToCart" value="Add To Cart >" onClick="window.location.href='<?php echo $cart_url; ?>';" class="addToCartButton"> <?php } else { echo 'Out Of Stock'; } ?> </td> </tr> <tr align="left"> <td colspan="2"><?php echo $pd_description; ?></td> </tr> </table> productList.php: <?php if (!defined('WEB_ROOT')) { exit; } $productsPerRow = 2; $productsPerPage = 8; //$productList = getProductList($catId); $children = array_merge(array($catId), getChildCategories(NULL, $catId)); $children = ' (' . implode(', ', $children) . ')'; $sql = "SELECT pd_id, pd_name, pd_price, pd_thumbnail, pd_qty, c.cat_id FROM tbl_product pd, tbl_category c WHERE pd.cat_id = c.cat_id AND pd.cat_id IN $children ORDER BY pd_name"; $result = dbQuery(getPagingQuery($sql, $productsPerPage)); $pagingLink = getPagingLink($sql, $productsPerPage, "c=$catId"); $numProduct = dbNumRows($result); // the product images are arranged in a table. to make sure // each image gets equal space set the cell width here $columnWidth = (int)(100 / $productsPerRow); ?> <table width="100%" border="0" cellspacing="0" cellpadding="20"> <?php if ($numProduct > 0 ) { $i = 0; while ($row = dbFetchAssoc($result)) { extract($row); if ($pd_thumbnail) { $pd_thumbnail = WEB_ROOT . 'images/product/' . $pd_thumbnail; } else { $pd_thumbnail = WEB_ROOT . 'images/no-image-small.png'; } if ($i % $productsPerRow == 0) { echo '<tr>'; } // format how we display the price $pd_price = displayAmount($pd_price); echo "<td width=\"$columnWidth%\" align=\"center\"><a href=\"" . $_SERVER['PHP_SELF'] . "?c=$catId&p=$pd_id" . "\"><img src=\"$pd_thumbnail\" border=\"0\" width=\"230\" height=\"170\"><br>$pd_name</a><br>Price : $pd_price<br>"; // format display add to cart echo "<input type=\"button\" name=\"btnAddToCart\" value=\"Add To Cart >\" onClick=\"window.location.href='<?php echo $cart_url;?>';\" >"; // if the product is no longer in stock, tell the customer if ($pd_qty <= 0) { echo "<br>Out Of Stock"; } echo "</td>\r\n"; if ($i % $productsPerRow == $productsPerRow - 1) { echo '</tr>'; } $i += 1; } if ($i % $productsPerRow > 0) { echo '<td colspan="' . ($productsPerRow - ($i % $productsPerRow)) . '"> </td>'; } } else { ?> <tr><td width="100%" align="center" valign="center">No products in this category</td></tr> <?php } ?> </table> <p align="center"><?php echo $pagingLink; ?></p> Product-functions.php: <?php require_once 'config.php'; /********************************************************* * PRODUCT FUNCTIONS **********************************************************/ /* Get detail information of a product */ function getProductDetail($pdId, $catId) { $_SESSION['shoppingReturnUrl'] = $_SERVER['REQUEST_URI']; // get the product information from database $sql = "SELECT pd_name, pd_description, pd_price, pd_image, pd_qty FROM tbl_product WHERE pd_id = $pdId"; $result = dbQuery($sql); $row = dbFetchAssoc($result); extract($row); $row['pd_description'] = nl2br($row['pd_description']); if ($row['pd_image']) { $row['pd_image'] = WEB_ROOT . 'images/product/' . $row['pd_image']; } else { $row['pd_image'] = WEB_ROOT . 'images/no-image-large.png'; } $row['cart_url'] = "cart.php?action=add&p=$pdId"; return $row; } ?> any help will be greatly appreciated
  8. Hi there, i follow a tutorial from www.phpwebcommerce.com and i'm having path problem for 'add to cart' button. Demo from phpwebcommerce: http://www.phpwebcommerce.com/plaincart/index.php I have modified some changes, i'm putting the 'add to cart' button to 1st level instead of 2nd level. Example, under all category (car & manga) i choose car, then inside car category list there is a 'add to cart' button under all car product instead of clicking inside and show 'add to cart' button. productDetail.php: <?php if (!defined('WEB_ROOT')) { exit; } $product = getProductDetail($pdId, $catId); // we have $pd_name, $pd_price, $pd_description, $pd_image, $cart_url extract($product); ?> <table width="100%" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center"><img src="<?php echo $pd_image; ?>" border="0" alt="<?php echo $pd_name; ?>" width="230" height="170"></td> <td valign="middle"> <strong><?php echo $pd_name; ?></strong><br> Price : <?php echo displayAmount($pd_price); ?><br> <?php // if we still have this product in stock // show the 'Add to cart' button if ($pd_qty > 0) { ?> <input type="button" name="btnAddToCart" value="Add To Cart >" onClick="window.location.href='<?php echo $cart_url; ?>';" class="addToCartButton"> <?php } else { echo 'Out Of Stock'; } ?> </td> </tr> <tr align="left"> <td colspan="2"><?php echo $pd_description; ?></td> </tr> </table> I copy this code out from productDetail.php: <input type="button" name="btnAddToCart" value="Add To Cart >" onClick="window.location.href='<?php echo $cart_url; ?>';"> productList.php: <?php if (!defined('WEB_ROOT')) { exit; } $productsPerRow = 2; $productsPerPage = 8; //$productList = getProductList($catId); $children = array_merge(array($catId), getChildCategories(NULL, $catId)); $children = ' (' . implode(', ', $children) . ')'; $sql = "SELECT pd_id, pd_name, pd_price, pd_thumbnail, pd_qty, c.cat_id FROM tbl_product pd, tbl_category c WHERE pd.cat_id = c.cat_id AND pd.cat_id IN $children ORDER BY pd_name"; $result = dbQuery(getPagingQuery($sql, $productsPerPage)); $pagingLink = getPagingLink($sql, $productsPerPage, "c=$catId"); $numProduct = dbNumRows($result); // the product images are arranged in a table. to make sure // each image gets equal space set the cell width here $columnWidth = (int)(100 / $productsPerRow); ?> <table width="100%" border="0" cellspacing="0" cellpadding="20"> <?php if ($numProduct > 0 ) { $i = 0; while ($row = dbFetchAssoc($result)) { extract($row); if ($pd_thumbnail) { $pd_thumbnail = WEB_ROOT . 'images/product/' . $pd_thumbnail; } else { $pd_thumbnail = WEB_ROOT . 'images/no-image-small.png'; } if ($i % $productsPerRow == 0) { echo '<tr>'; } // format how we display the price $pd_price = displayAmount($pd_price); echo "<td width=\"$columnWidth%\" align=\"center\"><a href=\"" . $_SERVER['PHP_SELF'] . "?c=$catId&p=$pd_id" . "\"><img src=\"$pd_thumbnail\" border=\"0\" width=\"230\" height=\"170\"><br>$pd_name</a><br>Price : $pd_price<br> <input type=\"button\" name=\"btnAddToCart\" value=\"Add To Cart >\" onClick=\"window.location.href='<?php echo $cart_url; ?>';\" >"; // if the product is no longer in stock, tell the customer if ($pd_qty <= 0) { echo "<br>Out Of Stock"; } echo "</td>\r\n"; if ($i % $productsPerRow == $productsPerRow - 1) { echo '</tr>'; } $i += 1; } if ($i % $productsPerRow > 0) { echo '<td colspan="' . ($productsPerRow - ($i % $productsPerRow)) . '"> </td>'; } } else { ?> <tr><td width="100%" align="center" valign="center">No products in this category</td></tr> <?php } ?> </table> <p align="center"><?php echo $pagingLink; ?></p> The code i copy from productDetail.php i paste in productList.php at line48, it show the 'add to cart' button but when i click on it, it cant add to my shopping cart and it show error: Notice: Undefined variable: cart_url in C:\Domains\xxxxxxxx\wwwroot\xxxxxxxx\plaincart\include\productList.php on line 48 Notice: Undefined variable: cart_url in C:\Domains\xxxxxxxx\wwwroot\xxxxxxxx\plaincart\include\productList.php on line 48 Notice: Undefined variable: cart_url in C:\Domains\xxxxxxxx\wwwroot\xxxxxxxx\plaincart\include\productList.php on line 48 Notice: Undefined variable: cart_url in C:\Domains\xxxxxxxx\wwwroot\xxxxxxxx\plaincart\include\productList.php on line 48 Will Appreciate For Any Help....Thank you in advanced & sorry for the bad English.
  9. Hi there Does anyone know where can i get php/mysql calculation weight & shipping cost tutorial ? Thank you in advanced!
  10. Hi there! im new to php , im having problem when upload image to server. Hope somebody can help me. i upload picture in admin CMS, the pic able to save in mysql but is not save in my server, the script below : $catImage = uploadImage('fleImage', SRV_ROOT . 'images/category/'); i have check the folder/directory name all correct but the picture wont save in my server images folder & i try this script but not working as well: $target_path = "images/category/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); i got this tutorial from : http://www.phpwebcommerce.com/ Thank You In Advance
  11. Thanks for helping cssfreakie, but this method can only select subcategory.....and even the subcategory can be select , when i click on save....it show errors . anyone know how to solve this problem ? i have been searching books & google..... still cant solve it. :'( any help will appreciate
  12. Hi there,I'm new to php...i'm following a tutorial from this site http://www.phpwebcommerce.com/index.php I just want to learn it & set up a simple store from this tutorial. My problem is, in the admin section when I try to add a new product the combo box doesn't allow me to select the category. It is listing the category, but it isn't allowing me to select it, if i cant select the category the whole product page won't be save. Below is the code: /* Generate combo box options containing the categories we have. if $catId is set then that category is selected */ function buildCategoryOptions($catId = 0) { $sql = "SELECT cat_id, cat_parent_id, cat_name FROM tbl_category ORDER BY cat_id"; $result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error()); $categories = array(); while($row = dbFetchArray($result)) { list($id, $parentId, $name) = $row; if ($parentId == 0) { // we create a new array for each top level categories $categories[$id] = array('name' => $name, 'children' => array()); } else { // the child categories are put int the parent category's array $categories[$parentId]['children'][] = array('id' => $id, 'name' => $name); } } // build combo box options $list = ''; foreach ($categories as $key => $value) { $name = $value['name']; $children = $value['children']; $list .= "<optgroup label=\"$name\">"; foreach ($children as $child) { $list .= "<option value=\"{$child['id']}\""; if ($child['id'] == $catId) { $list.= " selected"; } $list .= ">{$child['name']}</option>\r\n"; } $list .= "</optgroup>"; } return $list; } Thank you in advance.
  13. THANKS !!! u help me so much !! a BIG help from u !! THANK YOU SO MUCH !!! finally it works !!!!
  14. Thx for helping harristweed !! i already update my error to $display_block .="<p><strong><em>You are viewing:</em><br/> but the page still showing error.
  15. Hi !! i need some serious help here.....this code make me crazy :'( recently i have follow a tutorial about shopping cart, there is 2php file inside this (seestore.php & showitem.php). In this tutorial, i have create 4 table i) store_categories (id, badminton_title, badminton_desc) ii) store_items (id, badminton_id, item_title, item_price, item_desc, item_image) iii) store_items_size (item_id, item_size) iv) store_items_color (item_id, item_color) i have inserted values into each table. My problem now is, the 1st php (seestore.php) is working, it display the list, but there is problem in my 2nd php(showitem.php),the page cant show error. i have keep checking my coding but i still cant find where is my mistakes. Below is my php script: seestore.php <?php // connect to database $mysqli = mysqli_connect("xxxxx","xxxxx","xxxxx","xxxxx"); $display_block = "<h1>Product Categories</h1> <p><b>Select a category to see its items.</b></p>"; //show categories first $get_badminton_sql = "SELECT id, badminton_title, badminton_desc FROM store_categories ORDER BY badminton_title"; $get_badminton_res = mysqli_query($mysqli, $get_badminton_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows ($get_badminton_res) < 1) { $display_block = "<p><em>Sorry, no categories to browse.</em></p>"; } else { while ($badminton = mysqli_fetch_array($get_badminton_res)) { $badminton_id = $badminton['id']; $badminton_title = strtoupper (stripslashes($badminton['badminton_title'])); $badminton_desc = stripslashes($badminton['badminton_desc']); $display_block .="<p><strong><a href=\"".$_SERVER["PHP_SELF"]. "?badminton_id=".$badminton_id."\">".$badminton_title."</a></strong><br/>" .$badminton_desc."</p>"; if(isset($_GET["badminton_id"])) { if ($_GET["badminton_id"] == $badminton_id) { //get items $get_items_sql = "SELECT id, item_title, item_price FROM store_items WHERE badminton_id = '".$badminton_id."' ORDER BY item_title"; $get_items_res = mysqli_query($mysqli, $get_items_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows($get_items_res)<1) { $display_block = "<p><em>Sorry, no items in this category.</em></p>"; } else { $display_block .="<ul>"; while ($items = mysqli_fetch_array ($get_items_res)) { $item_id = $items['id']; $item_title = stripslashes($items['item_title']); $item_price = $items['item_price']; $display_block .="<li><a href=\"showitem.php? item_id=".$item_id."\">".$item_title."</a> </strong>(\$".$item_price.")</li>"; } $display_block .="</ul>"; } //free results mysqli_free_result($get_items_res); } } } } //free results mysqli_free_result($get_badminton_res); //close connection to MySQL mysqli_close($mysqli); ?> <html> <head> <title>My Categories</title> </head> <body> <?php echo $display_block; ?> </body> </html> showitem.php <?php ///displaying page //connect to database $mysqli = mysqli_connect("xxxxx","xxxxx","xxxxx","xxxxx"); $display_block = "<h1>My Store - Item Detail</h1>"; //validate item (/////////// i don't really understand this part , and personally i think the error come from here) $get_item_sql = "SELECT c.id as badminton_id, c.badminton_title, si.item_title, si.item_price, si.item_desc, si.item_image FROM store_items AS si LEFT JOIN store_categories AS c on c.id = si.badminton_id WHERE si.id = '".$_GET["item_id"]."'"; $get_item_res = mysqli_query($mysqli, $get_item_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows($get_item_res) <1) { //invalid item $display_block .="<p><em>Invalid item selection.</em></p>"; } else { //valid item, get info while ($item_info = mysqli_fetch_array($get_item_res)) { $badminton_id = $item_info['badminton_id']; $badminton_title = strtoupper(stripslashes($item_info['badminton_title'])); $item_title = stripslashes($item_info['item_title']); $item_price = $item_info['item_price']; $item_desc = stripslashes($item_info['item_desc']); $item_image = $item_info['item_image']; } ///make breadcrumb trail $display_block .=<p><strong><em>You are viewing:</em><br/> <a href=\"seestore.php?badminton_id=".$badminton_id."\">".$badminton_title."</a> > ".$item_title."</strong></p> <table cellpadding=\"3\" cellspacing=\"3\"> <tr> <td valign=\"middle\" align=\"center\"> <img src=\"".$item_image."\"/></td> <td valign=\"middle\"><p><strong>Description:</strong><br/>". $item_desc."</p> <p><strong>Price:</strong> \$".$item_price."</p>"; ///free result mysqli_free_result($get_item_res); ///get colors $get_colors_sql = "SELECT item_color FROM store_items_color WHERE item_id = '".$GET["item_id"]."' ORDER BY item_color"; $get_colors_res = mysqli_query($mysqli, $get_colors_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows($get_colors_res) >0) { $display_block .="<p><strong>Available Colors:</strong><br/>"; while ($colors = mysqli_fetch_array($get_colors_res)) { item_color = $colors['item_color']; $display_block .=$item_color."<br/>"; } } //free result mysqli_free_result($get_colors_res); //get sizes $get_sizes_sql = "SELECT item_size FROM store_items_size WHERE item_id = ".$_GET["item_id"]."ORDER BY item_size"; $get_sizes_res = mysqli_query($mysqli, $get_sizes_sql) or die (mysqli_error($mysqli)); if (mysqli_num_rows($get_sizes_res) >0) { $display_block .="<p><strong>Available Sizes:</strong><br/>"; while ($sizes = mysqli_fetch_array ($get_sizes_res)) { $item_size = $sizes['item_size']; $display_block .=$item_size."<br/>"; } } //free result mysqli_free_result($get_sizes_res); $display_block .=" </td> </tr> </table>"; } ?> <html> <head> <title>My Store</title> </head> <body> <?php echo $display_block; ?> </body> </html> Thanks for helping & sorry for bad English.
  16. Hi there! im new to php , im having problem when receiving email from enquiry from i have created below. i had create the form, after user click on submit, the information will store in mysql and send a copy to email account. My problem is, in the form i had 'name','email','contact', 'subject','message' but i only receive 'message' from email,other information not receiving (no problem with mysql). i have tried few method like adding variable ...it cant works as well. hope u guys able to help me. Thank you in advance <html> <title>Login Script</title> <body> <?php function insertData($msg) // <-- add rest $_post data here.. { // Connects to your Database mysql_connect("xxxxxx","xxxxxx","xxxxxx") or die(mysql_error()); mysql_select_db("xxxxxx_enquiry") or die(mysql_error()); // now we insert it into the database $insert = "INSERT INTO enquiry (name, email, cont_number, subject, msg) VALUES ('".$_POST['name']."', '".$_POST['email']."', '".$_POST['cont_number']."', '".$_POST['subject']."','".$_POST['msg']."')"; if($add_member = mysql_query($insert)) { sendMail(($_POST['msg']),($_POST['email'])); } } function sendMail($message) { $to = 'desmond@xxxxx.com'; $from = 'From: xxxxx.com'; mail($to, "You have a new message", $message, $from); $message="Thank You !! <br> Form has been submitted"; } ?> <?php function error_bool($error, $field) { if($error[$field]) { print("<td style=color:red>"); } else { print("<td>"); } } ////////////////// function show_form() { global $HTTP_POST_VARS, $_POST, $print_again, $error; ?> <script type="text/javascript"> <!-- function MM_validateForm() { //v4.0 if (document.getElementById){ var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } } //--> </script> <h2 align="center"> Enquiry Form</h2> <form action="<?php echo $_SERVER['../PHP_SELF']; ?>" method="post"> <table align="center" cellpadding="3"> <tr> <?php error_bool($error, "name"); ?> Name </td> <td>:<input name="name" type="text" id="name" onBlur="MM_validateForm('name','','R');return document.MM_returnValue" value="<? echo $_POST["name"]; ?>" SIZE="33"></td> </tr> <tr> <?php error_bool($error, "email"); ?> Email </td> <td>:<input name="email" type="text" id="email" onBlur="MM_validateForm('email','','RisEmail');return document.MM_returnValue" value="<? echo $_POST["email"]; ?>" SIZE="33"></td> </tr> <tr><td>Contact No. </td><td> :<input name="cont_number" type="text" id="cont_number" onBlur="MM_validateForm('cont_number','','RisNum');return document.MM_returnValue" SIZE="33" maxlength="10"> </td></tr> <tr><td>Subject </td><td> :<input type="text" name="subject" SIZE="33" maxlength="25"> </td></tr> <tr><td>Your Message :</td><td> <textarea name="msg" cols="27" rows="5" wrap="virtual"></textarea> </td></tr> <tr> <td><th colspan=4 align="right"> <input type="reset" value="Clear"><input type="submit" name="Submit" value="Submit"></td> </th><td> </td> </tr> </table> </form> <?php } if(isset($_POST["Submit"])) { check_form(); } else { show_form(); } function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } function check_form() { global $_POST, $error, $print_again; $error['name'] = false; if($_POST["name"]=="") { $error['name'] = true; $print_again = true; $message="The name field is empty<br>"; } if(!check_email_address($_POST['email'])) { $error['email'] = true; $print_again = true; $message.="Either Field Empty or Invalid Email ID <br>"; } if($print_again) { show_form(); } else { show_form(); insertData($_POST['msg']); // <-- call the function (add the rest of post data here.) //$message="Thank You !! <br> Form has been submitted"; // <-- move this to the sendMail function } echo "$message"; } ?> </body> </html>
  17. Hi there, hope u guys able to help. I'm have created a enquiry form where I want these actions to run when a button is submitted: 1. Insert data from form fields into my database 2. When data is inserted into database, then send an e-mail (multiple email user) to the address with the form fields. The e-mail is carrying the form fields. so ...what I need now is how to send the form field to email. Insert the data into my table in my database,then send en e-mail. <? // Connects to your Database mysql_connect("xxxxxx","xxxxxx","xxxxxx") or die(mysql_error()); mysql_select_db("xxxxxx") or die(mysql_error()); // now we insert it into the database $insert = "INSERT INTO enquiry (name, email, cont_number, subject, msg) VALUES ('".$_POST['name']."', '".$_POST['email']."', '".$_POST['cont_number']."', '".$_POST['subject']."','".$_POST['msg']."')"; $add_member = mysql_query($insert); ?> <?php function error_bool($error, $field) { if($error[$field]) { print("<td style=color:red>"); } else { print("<td>"); } } function show_form() { global $HTTP_POST_VARS, $print_again, $error; ?> <h2 align="center"> Enquiry Form</h2> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table align="center" cellpadding="3"> <tr> <?php error_bool($error, "name"); ?> Name </td> <td>:<input name="name" type="text" id="name" SIZE="33" value="<? echo $_POST["name"]; ?>"></td> </tr> <tr> <?php error_bool($error, "email"); ?> Email </td> <td>:<input name="email" type="text" id="email" SIZE="33" value="<? echo $_POST["email"]; ?>"></td> </tr> <tr><td>Contact No. </td><td> :<input type="text" name="cont_number" SIZE="33" maxlength="10"> </td></tr> <tr><td>Subject </td><td> :<input type="text" name="subject" SIZE="33" maxlength="25"> </td></tr> <tr><td>Your Message :</td><td> <textarea name="msg" cols="27" rows="5" wrap="virtual"></textarea> </td></tr> <tr> <td><th colspan=4 align="right"> <input type="reset" value="CLEAR"><input type="submit" name="Submit" value="Submit"></td> </th><td> </td> </tr> </table> </form> <? } if(isset($_POST["Submit"])) { check_form(); } else { show_form(); } function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } function check_form() { global $HTTP_POST_VARS, $error, $print_again; $error['name'] = false; if($_POST["name"]=="") { $error['name'] = true; $print_again = true; $message="The name field is empty<br>"; } if(!check_email_address($_POST['email'])) { $error['email'] = true; $print_again = true; $message.="Either Field Empty or Invalid Email ID <br>"; } if($print_again) { show_form(); } else { show_form(); $message="Thank You !! <br> Form has been submitted"; } echo "$message"; } ?> </body> </html> How do i do this? Thank you in advanced and sorry for bad English. Best regards, Desmond
  18. hi everyone ! im new to php script, hope u guys able to help me. Thank you in advance. Im using localhost xampp, i have activate my smtp and set smtp_port to 25 , smtp = localhost. when i run the script , error message show: Notice: Undefined variable: email in C:\xampp\htdocs\sendmymail.php on line 54 Notice: Undefined index: in C:\xampp\htdocs\sendmymail.php on line 54 Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\xampp\htdocs\sendmymail.php on line 56 newsletter sent to: here is my php script, i have highlighted line 56 & 54 : <?php include ("ch19_include.php"); if (!$_POST) { //haven't seen the form, so display it echo "<html> <head><title>Send a Newsletter</title></head> <body> <h1>Send a Newsletter</h1> <form method=\"post\" action=\" ".$_SERVER["PHP_SELF"]."\"> <p><strong>Subject:</strong><br/> <input type=\"text\" name=\"subject\" size=\"30\"</p> <p><storng>Mail Body:</storng><br/> <textarea name=\"message\" cols=\"50\" rows=\"10\" wrap=\"virtual\"></textarea> <p><input type=\"submit\" name=\"submit\" value=\"Send It\"></p> </form> </body> </html>"; } else if ($_POST) { //want to send form, so check for required fields if (($_POST["subject"] == "")|| ($_POST["message"] == "")) { header("Location: sendmymail.php"); exit; } //connect to database doDB(); if (mysqli_connect_errno()) { // if connection fails, stop script execution printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { //otherwise, get emails from subscribers list $sql = "SELECT email FROM subscribers"; $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //create a From: mailheader $mailheaders = "From: Your Mailling List <abc@gmail.com>"; //loop through results and send mail while ($row = mysqli_fetch_array ($result)) { set_time_limit(0); $email=$row ["$email"]; mail("email", stripslashes($_POST["subject"]), stripslashes($_POST["message"]), $mailheaders); echo "newsletter sent to: ".$email."<br/>"; } mysqli_free_result($result); mysqli_close($mysqli); } } ?>
  19. hello experts ! im new to php script, hope u guys able to help. Thx in advance . I'm following a tutorial from this site: http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_(blob_storage).xml and i run the code, error occur :'( (i highlighted line 27) : Parse error: syntax error, unexpected T_STRING in C:\xampp\htdocs\testing.php on line 27 This is my php script: <?php $db_host = 'localhost'; // don't forget to change $db_user = 'root'; $db_pwd = '123456'; $database = 'test'; $table = 'ae_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone ////create sql-table CREATE TABLE 'ae_gallery' ( 'id' int(11) NOT NULL AUTO_INCREMENT, 'title' varchar(64) character SET utf8 NOT NULL, 'ext' varchar( 8 ) character SET utf8 NOT NULL, 'image_time' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 'data' mediumblob NOT NULL, PRIMARY KEY (`id`) ); if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($ae_gallery)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)';// use (empty title) string if ($_POST['password'] != $password) // cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['photo'])) { @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']); // Get image type. // We use @ to omit errors if ($imtype == 3) // cheking image type $ext="png"; // to use it later in HTTP headers elseif ($imtype == 2) $ext="jpeg"; elseif ($imtype == 1) $ext="gif"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: image uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Photo deleted'; } } } elseif (isset($_GET['show'])) { $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $image_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $image_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } ?> <html><head> <title>MySQL Image Gallery Example</title> </head> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?> <br> <a href="<?=$PHP_SELF?>">reload page</a> <!-- I've added reloading link, because refreshing POST queries is not good idea --> </p> <?php } ?> <h1><i>Image gallery</i></h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else { echo '<ul>'; while(list($id, $image_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$image_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> </form> <h2>Upload new image:</h2> <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br> <input type="text" name="title" id="title" size="64"><br><br> <label for="photo">Photo:</label><br> <input type="file" name="photo" id="photo"><br><br> <label for="password">Password:</label><br> <input type="password" name="password" id="password"><br><br> <input type="submit" value="upload"> </form>
  20. hello everyone....i am new for this script, hope u guys able to help me. Thank you in advance! im using xampp for localhost, all .php file i place it in xampp\htdocs ( i create a uploads folder outside the htdocs, c:\xampp\uploads) This is the error message i get after i upload the file: Notice: Undefined variable: FILES in C:\xampp\htdocs\upload_file.php on line 15 Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\xampp\htdocs\upload_file.php on line 15 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\xampp\tmp\phpAE.tmp' to '../uploads/' in C:\xampp\htdocs\upload_file.php on line 15 Your file could not be uploaded because: Something unforeseen happened.. following is my upload_file.php script , i highlighted on line 15: <!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>Upload a File</title> </head> <body> <?php ///Script - 11.4 - upload_file.php /* This script displays and handles an HTML form. this script takes a file upload and stored it on the servers */ if(isset($_POST['submitted'])) { //Handle the form //Try to move the upload file: if (move_uploaded_file ($_FILES['thefile']['tmp_name'],"../uploads/{$FILES['thefile']['name']}")){ print '<p>Your file has been uploaded.</p>'; }else { //problem!! print '<p style="color:red;">Your file could not be uploaded because: '; ///print a message based upon the error: switch ($_FILES['thefile']['error']) { case 1: print 'The file exceeds the upload_max_filesize setting in php.ini'; break; case 2: print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form'; break; case 3: print 'The file was only partially uploaded'; break; case 4: print 'No file was uploaded'; break; case 6: print 'The temporary folder does not exist.'; break; default: print 'Something unforeseen happened.'; break; } print '.</p>'; /////complete the paragraph. } // End of move_uploaded_file()IF } // End of submission IF //Leave PHP and display the form: ?> <form action="upload_file.php" enctype="multipart/form-data" method="post"> <p>Upload a file using this form:</p> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> <p><input type="file" name="thefile" /></p> <p><input type="submit" name="submit" value="Upload This File" /></p> <input type="hidden" name="submitted" value="true" /> </form> </body> </html>
  21. thank you for pointing out the error ! solved my problem !!!
  22. hello everyone....i am new for this script, hope u guys able to help me. Thank you in advance! i have created register.php and it works, but i try login then the error message show: Notice: Undefined index: password in C:\xampp\htdocs\login.php on line 26 The username and password you entered do not match those on file im using xampp for localhost, all .php file i place it in xampp\htdocs for the users.txt( i create a users folder outside the htdocs, c:\xampp\users & i place my users.txt inside the users folder) following is my login.php script: <!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>Login</title> </head> <body> <?php /// Script 11.7 - login.php /*This script logs a user in by check the stored values in text file. */ if(isset($_POST['submitted'])) { //handle the form $loggedin = FALSE; //not currently logged in //Enable auto_detect_line_settings: ini_set('auto_detect_line_endings',1); //open the file: $fp = fopen('../users/users.txt','rb'); //Loop through the file: while($line = fgetcsv($fp,100,"\t")) { //Check the file data against the submitted data: if(($line[0] == $_POST['username'])AND($line[1] == md5(trim($_POST['password'])))) { $loggedin = TRUE; //correct username/password combination //stop looping through the file: break; } //End of IF } //End of While fclose($fp); //Close the file //print a message: if($loggedin) { print '<p>You are now logged in.</p>'; } else { print '<p style="color:red;">The username and password you entered do not match those on file</p>'; } }else { //Display the form //Leave php and display the form: ?> <form action="login.php" method="post"> <p>Username: <input type="text" name="username" size="20" /></p> <p>Password: <input type="password" name="password1" size="20" /></p> <input type="submit" name="submit" value="Login" /> <input type="hidden" name="submitted" value="true" /> </form> <?php }//end of submission IF. ?> </body> </html>
×
×
  • 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.