PHP - Cart Help, Changing Button Disply
I am using OPENCART and i would like to have my "Add To Cart" button read "Pre Order" when the stock is 0. This is just for now i will want to change it later to make the button reflect certain stock statuses.
For now i would like some help cleaning this up so it work Code: [Select] $x = "PRE ORDER"; define("X"); <?php if ($product_info['quantity'] <= 0) { $x = "<?php echo $button_cart; ?>" } else { echo $x } ?> <a id="button-cart" class="button"><span>$x</span></a></div> Similar TutorialsWhy does this button at the end of the file not add anything to the cart? <td align="right" class="main"><?php echo tep_draw_button(IMAGE_BUTTON_IN_CART, 'cart', null, 'primary'); ?></td> Code: [Select] <form name="cart_multi" method="post" action="<?php echo tep_href_link(FILENAME_SHOPPING_CART, tep_get_all_get_params(array('action')) . 'action=add_multi', 'NONSSL'); ?>"> <script language=javascript> function changeValue(textObject,delta){ var myVal = parseInt(textObject.value); if (myVal == NaN) { myVal = 0; } else { myVal = myVal + delta; } /* check that it is not negetive */ if (myVal < 0) { myVal = 0; } textObject.value = myVal; return; } </script> <?php /* $Id$ adapted for Separate Pricing Per Customer v4.2 2007/08/23 osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2010 osCommerce Released under the GNU General Public License */ $listing_split = new splitPageResults($listing_sql, MAX_DISPLAY_SEARCH_RESULTS, 'p.products_id'); ?> <div class="contentText"> <?php if ( ($listing_split->number_of_rows > 0) && ( (PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3') ) ) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td align="right" class="main"><?php echo tep_draw_button(IMAGE_BUTTON_IN_CART, 'cart', null, 'primary'); ?></td> </tr> </table> <br> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $listing_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $listing_split->display_count(TEXT_DISPLAY_NUMBER_OF_PRODUCTS); ?></span> </div> <br /> <?php } $prod_list_contents = '<div class="ui-widget infoBoxContainer">' . ' <div class="ui-widget-header ui-corner-top infoBoxHeading">' . ' <table border="0" width="100%" cellspacing="0" cellpadding="2" class="productListingHeader">' . ' <tr>'; for ($col=0, $n=sizeof($column_list); $col<$n; $col++) { $lc_align = ''; switch ($column_list[$col]) { case 'PRODUCT_LIST_MODEL': $lc_text = TABLE_HEADING_MODEL; $lc_align = ''; break; case 'PRODUCT_LIST_NAME': $lc_text = TABLE_HEADING_PRODUCTS; $lc_align = ''; break; case 'PRODUCT_LIST_MANUFACTURER': $lc_text = TABLE_HEADING_MANUFACTURER; $lc_align = ''; break; case 'PRODUCT_LIST_PRICE': $lc_text = TABLE_HEADING_PRICE; $lc_align = 'right'; break; case 'PRODUCT_LIST_QUANTITY': $lc_text = TABLE_HEADING_QUANTITY; $lc_align = 'right'; break; case 'PRODUCT_LIST_MIN_ORDER_QTY': $lc_align = 'center'; $lc_text = ' ' . TABLE_HEADING_MIN_ORDER_QTY . ' '; break; case 'PRODUCT_LIST_WEIGHT': $lc_text = TABLE_HEADING_WEIGHT; $lc_align = 'right'; break; case 'PRODUCT_LIST_IMAGE': $lc_text = TABLE_HEADING_IMAGE; $lc_align = 'center'; break; case 'PRODUCT_LIST_BUY_NOW': $lc_text = TABLE_HEADING_BUY_NOW; $lc_align = 'center'; break; } if ( ($column_list[$col] != 'PRODUCT_LIST_BUY_NOW') && ($column_list[$col] != 'PRODUCT_LIST_IMAGE') ) { $lc_text = tep_create_sort_heading($HTTP_GET_VARS['sort'], $col+1, $lc_text); } $prod_list_contents .= ' <td' . (tep_not_null($lc_align) ? ' align="' . $lc_align . '"' : '') . '>' . $lc_text . '</td>'; } $prod_list_contents .= ' </tr>' . ' </table>' . ' </div>'; if ($listing_split->number_of_rows > 0) { $rows = 0; $listing_query = tep_db_query($listing_split->sql_query); // BOF Separate Pricing per Customer $no_of_listings = tep_db_num_rows($listing_query); // global variable (session) $sppc_customer_group_id -> local variable customer_group_id if(isset($_SESSION['sppc_customer_group_id']) && $_SESSION['sppc_customer_group_id'] != '0') { $customer_group_id = $_SESSION['sppc_customer_group_id']; } else { $customer_group_id = '0'; } while ($_listing = tep_db_fetch_array($listing_query)) { $listing[] = $_listing; $list_of_prdct_ids[] = $_listing['products_id']; } // next part is a debug feature, when uncommented it will print the info that this module receives /* echo '<pre>'; print_r($listing); echo '</pre>'; */ // get all product prices for products with the particular customer_group_id // however not necessary for customer_group_id = 0 if ($customer_group_id != '0') { $pg_query = tep_db_query("select pg.products_id, customers_group_price as price from " . TABLE_PRODUCTS_GROUPS . " pg where products_id in (" . implode(',', $list_of_prdct_ids) . ") and pg.customers_group_id = '" . $customer_group_id . "'"); // $no_of_pg_products = tep_db_num_rows($pg_query) ; while ($pg_array = tep_db_fetch_array($pg_query)) { $new_prices[] = array ('products_id' => $pg_array['products_id'], 'products_price' => $pg_array['price'], 'specials_new_products_price' => '', 'final_price' => $pg_array['price']); } for ($x = 0; $x < $no_of_listings; $x++) { // replace products prices with those from customers_group table if(!empty($new_prices)) { for ($i = 0; $i < count($new_prices); $i++) { if( $listing[$x]['products_id'] == $new_prices[$i]['products_id'] ) { $listing[$x]['products_price'] = $new_prices[$i]['products_price']; $listing[$x]['final_price'] = $new_prices[$i]['final_price']; } } } // end if(!empty($new_prices) $listing[$x]['specials_new_products_price'] = ''; // makes sure that a retail specials price doesn't carry over to another customer group $listing[$x]['final_price'] = $listing[$x]['products_price']; // final price should not be the retail special price } // end for ($x = 0; $x < $no_of_listings; $x++) } // end if ($customer_group_id != '0') // an extra query is needed for all the specials $specials_query = tep_db_query("select products_id, specials_new_products_price from " . TABLE_SPECIALS . " where products_id in (" . implode(',', $list_of_prdct_ids) . ") and status = '1' and customers_group_id = '" . $customer_group_id . "'"); while ($specials_array = tep_db_fetch_array($specials_query)) { $new_s_prices[] = array ('products_id' => $specials_array['products_id'], 'products_price' => '', 'specials_new_products_price' => $specials_array['specials_new_products_price'] , 'final_price' => $specials_array['specials_new_products_price']); } // add the correct specials_new_products_price and replace final_price for ($x = 0; $x < $no_of_listings; $x++) { if(!empty($new_s_prices)) { for ($i = 0; $i < count($new_s_prices); $i++) { if( $listing[$x]['products_id'] == $new_s_prices[$i]['products_id'] ) { $listing[$x]['specials_new_products_price'] = $new_s_prices[$i]['specials_new_products_price']; $listing[$x]['final_price'] = $new_s_prices[$i]['final_price']; } } } // end if(!empty($new_s_prices) } // end for ($x = 0; $x < $no_of_listings; $x++) $prod_list_contents .= ' <div class="ui-widget-content ui-corner-bottom productListTable">' . ' <table border="0" width="100%" cellspacing="0" cellpadding="2" class="productListingData">'; // while ($listing = tep_db_fetch_array($listing_query)) { (was original code) for ($x = 0; $x < $no_of_listings; $x++) { $rows++; $prod_list_contents .= ' <tr>'; for ($col=0, $n=sizeof($column_list); $col<$n; $col++) { switch ($column_list[$col]) { case 'PRODUCT_LIST_MODEL': $prod_list_contents .= ' <td>' . $listing[$x]['products_model'] . '</td>'; break; case 'PRODUCT_LIST_NAME': if (isset($HTTP_GET_VARS['manufacturers_id']) && tep_not_null($HTTP_GET_VARS['manufacturers_id'])) { $prod_list_contents .= ' <td><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $HTTP_GET_VARS['manufacturers_id'] . '&products_id=' . $listing[$x]['products_id']) . '">' . $listing[$x]['products_name'] . '</a></td>'; } else { $prod_list_contents .= ' <td><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing[$x]['products_id']) . '">' . $listing[$x]['products_name'] . '</a></td>'; } break; case 'PRODUCT_LIST_MANUFACTURER': $prod_list_contents .= ' <td><a href="' . tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . $listing[$x]['manufacturers_id']) . '">' . $listing[$x]['manufacturers_name'] . '</a></td>'; break; case 'PRODUCT_LIST_PRICE': if (tep_not_null($listing[$x]['specials_new_products_price'])) { $prod_list_contents .= ' <td align="right"><del>' . $currencies->display_price($listing[$x]['products_price'], tep_get_tax_rate($listing[$x]['products_tax_class_id'])) . '</del> <span class="productSpecialPrice">' . $currencies->display_price($listing[$x]['specials_new_products_price'], tep_get_tax_rate($listing[$x]['products_tax_class_id'])) . '</span></td>'; } else { $prod_list_contents .= ' <td align="right">' . $currencies->display_price($listing[$x]['products_price'], tep_get_tax_rate($listing[$x]['products_tax_class_id'])) . '</td>'; } break; case 'PRODUCT_LIST_QUANTITY': $prod_list_contents .= ' <td align="right">' . $listing[$x]['products_quantity'] . '</td>'; break; case 'PRODUCT_LIST_MIN_ORDER_QTY': $prod_list_contents .= ' <td align="right">' . $lc_text = ' ' . $listing[$x]['products_min_order_qty'] . ' '; break; case 'PRODUCT_LIST_WEIGHT': $prod_list_contents .= ' <td align="right">' . $listing[$x]['products_weight'] . '</td>'; break; case 'PRODUCT_LIST_IMAGE': if (isset($HTTP_GET_VARS['manufacturers_id']) && tep_not_null($HTTP_GET_VARS['manufacturers_id'])) { $prod_list_contents .= ' <td align="center"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $HTTP_GET_VARS['manufacturers_id'] . '&products_id=' . $listing[$x]['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $listing[$x]['products_image'], $listing[$x]['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a></td>'; } else { $prod_list_contents .= ' <td align="center"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing[$x]['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $listing[$x]['products_image'], $listing['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a></td>'; } break; case 'PRODUCT_LIST_BUY_NOW': $prod_list_contents .= ' <td align="center">' . $lc_text = '<input type=button value=" -1" onclick="javascript:changeValue(document.getElementById(\'add_id_'.$listing[$x]['products_id'].'\'),-1);return false;"><input type="text" name="add_id['.$number_of_products.']" id="add_id_'.$listing[$x]['products_id'].'" value="0" size="3"><input type=button value="+1" onclick="javascript:changeValue(document.getElementById(\'add_id_'.$listing[$x]['products_id'].'\'),1);return false;">'; $lc_text .= '<input type="hidden" name="products_id['.$number_of_products.']" value="'.$listing[$x]['products_id'].'">'; break; } } $prod_list_contents .= ' </tr>'; } $prod_list_contents .= ' </table>' . ' </div>' . '</div>'; echo $prod_list_contents; } else { ?> <p><?php echo TEXT_NO_PRODUCTS; ?></p> <?php } if ( ($listing_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3')) ) { ?> <br /> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $listing_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $listing_split->display_count(TEXT_DISPLAY_NUMBER_OF_PRODUCTS); ?></span> </div> <br> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td align="right" class="main"><?php echo tep_draw_button(IMAGE_BUTTON_IN_CART, 'cart', null, 'primary'); ?></td> </tr> </table> </form> <?php } ?> </div> 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: Code: [Select] <?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: Code: [Select] <input type="button" name="btnAddToCart" value="Add To Cart >" onClick="window.location.href='<?php echo $cart_url; ?>';"> productList.php: Code: [Select] <?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. 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: Code: [Select] <?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: Code: [Select] <?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: Code: [Select] <?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 I am querying a database and trying to display the names of categories in a drop-down menu. My problem is that the names are not visible. I have the following code: $result = mysql_query('SELECT name FROM category') or die(mysql_error()); echo('Choose a category'); echo('<select name="category">'); echo('<option value="general" >general</option>'); while($row = mysql_fetch_array($result)){ echo('<option style="color:black;" value = "'.$row['name'].'">'.$row['name'].'</option>'); } echo('</select><br /><br />'); The query is good and executing the query retrieves the expected number of results. My dropdown box is the proper length and width (showing that it is trying to print the names); however, nothing is displayed. Any ideas? Hey again, Still on the same project but now doing the cart page. I've been bringing my skills up to date a lot doing this project, however, having said that I now can't figure out why my cart is not adding the items to the cart, i've checked the post data and the quantity is set to 1. Would really appreciate someone having a look at it and hopefully can see what i'm missing. you can see what it should look like (well so far lol) at here in my sandbox site. thanks again. (p.s. The parts are all over the place on the page, so thought better put whole page, sorry if shouldn't have done that) <?php // Initialize the session session_start(); // Include config file require_once "dbcontroller.php"; $db_handle = new DBController(); if(!empty($_GET["action"])) { switch($_GET["action"]) { case "add": if(!empty($_POST["quantity"])) { $productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_code='" . $_GET["product_code"] . "'"); $itemArray = array($productByCode[0]["product_code"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_code'=>$productByCode[0]["product_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["img1"])); if(!empty($_SESSION["cart_item"])) { if(in_array($productByCode[0]["product_code"],array_keys($_SESSION["cart_item"]))) { foreach($_SESSION["cart_item"] as $k => $v) { if($productByCode[0]["product_code"] == $k) { if(empty($_SESSION["cart_item"][$k]["quantity"])) { $_SESSION["cart_item"][$k]["quantity"] = 0; } $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"]; } } } else { $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); } } else { $_SESSION["cart_item"] = $itemArray; } } break; case "remove": if(!empty($_SESSION["cart_item"])) { foreach($_SESSION["cart_item"] as $k => $v) { if($_GET["product_code"] == $k) unset($_SESSION["cart_item"][$k]); if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } break; case "empty": unset($_SESSION["cart_item"]); break; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>LeaversHoodies.ie</title> <!-- Bootstrap --> <link href="css/bootstrap-4.4.1.css" rel="stylesheet"> <link href="css/accordian.css" rel="stylesheet"> </head> <body> <?php include 'header_student.php'; ?> <br /> <?php $school_page = "ravenswell"; $sql = "SELECT * FROM schools WHERE school_page = '$school_page'"; if($result = mysqli_query($conn, $sql)) while($row = mysqli_fetch_array($result)) { ?> <h3 class="text-center">Student Ordering Page For</h3> <h2 class="text-center" style="text-transform:uppercase;"><?php echo $row['school_name']; ?></h2> <hr style="width: 50%; text-align:center; border: 2px solid #00aeef; border-radius: 5px; margin: 0 auto;"> <br /> <div class="container"> <div class="row"> <div class="col"> <?php $path = "images/schools/"; $file = $row["logo"]; if(!empty($row['logo'])) { echo '<img src="'.$path.$file.'" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } else { echo '<img src="images/schools/140x140.gif" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } ?></div> <div class="col-6"> <h5>These are the garments your school has choosen :</h5><br /> <?php $school_id = $row["school_id"]; } var_dump($_SESSION); var_dump($_POST); $product_array = $db_handle->runQuery("SELECT * FROM choices INNER JOIN products USING (product_code) INNER JOIN colours USING (colour_id) WHERE school_id = '$school_id'"); if (!empty($product_array)) { foreach($product_array as $key=>$value){ ?> <div class="container"> <div class="row"> <div class="col-5" style="text-align:left;"> <img src="images/products/<?php echo $product_array[$key]["img1"]; ?>" alt="<?php echo $product_array[$key]["product_code"]; ?>" style="position:relative; top:0; width:200px; display:block;"> </div> <div class="col-7"> <h5><?php echo $product_array[$key]["product_name"]; ?></h5><p> in <?php echo $product_array[$key]["colour_name"]; ?></p> <p style="font-size:12px;"><?php echo $product_array[$key]["description"]; ?></p> <?php $comment = $product_array[$key]["comment"]; if (empty($comment)) { echo ""; } else { ?> <p style="font-size:12px;"><b>A note from your teacher:</b> <br /> <?php echo $product_array[$key]["comment"]; ?></p> <?php }; ?> <form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]["product_code"]; ?>" method="post"> <?php $product = $product_array[$key]["product_code"]; ?> Please select your size : <select id="size" name="size"> <?php $sql1 = "SELECT DISTINCT * FROM sizes WHERE product_code = '$product'"; if($result1 = mysqli_query($conn, $sql1)) while($row3 = mysqli_fetch_array($result1)){ echo "<option value='" . $row3['size'] . "'>" . $row3['size'] . "</option>"; } else { echo "nothing to see here"; } ?> </select> <br /><br /> <div class="number">How many do you want: <input type="number" style="font-size:12px;" id="quantity" name="quantity" value="1" min="1" max="5"><br /> Price : <?php echo "€".$product_array[$key]["price"]; ?> </div> <input type="hidden" id="product_code" value="<?php echo $product; ?>"><br /> <input type="submit" style="font-size:12px;" value="Add to Order" class="btnAddAction"> </form> </div> </div> <br /><hr style="width: 90%; text-align:center; border: 1px solid #00aeef; border-radius: 5px; margin: 0 auto;"><br /> </div> <?php } } else { echo "No Schools by that name registered."; } ?> </div> <div class="col-3"> <div style="border: 1px solid #d3d3d3; padding: 10px; border-radius: 5px; margin-top:30px;"> Your Order: </div> </div> </div> <div class="txt-heading">Shopping Cart</div> <a id="btnEmpty" href="student_order.php?schoolname=<?php echo $school_page; ?>?action=empty">Empty Cart</a> <?php if(isset($_SESSION["cart_item"])){ $total_quantity = 0; $total_price = 0; ?> <table class="tbl-cart" cellpadding="10" cellspacing="1"> <tbody> <tr> <th style="text-align:left;">Name</th> <th style="text-align:left;">Code</th> <th style="text-align:right;" width="5%">Quantity</th> <th style="text-align:right;" width="10%">Unit Price</th> <th style="text-align:right;" width="10%">Price</th> <th style="text-align:center;" width="5%">Remove</th> </tr> <?php foreach ($_SESSION["cart_item"] as $item){ $item_price = $item["quantity"]*$item["price"]; ?> <tr> <td><img src="images/products/<?php echo $item["img1"]; ?>" class="cart-item-image" /><?php echo $item["product_name"]; ?></td> <td><?php echo $item["product_code"]; ?></td> <td style="text-align:right;"><?php echo $item["quantity"]; ?></td> <td style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td> <td style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td> <td style="text-align:center;"><a href="student_order.php?schoolname=<?php echo $school_page; ?>?action=remove&product_code=<?php echo $item["product_code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td> </tr> <?php $total_quantity += $item["quantity"]; $total_price += ($item["price"]*$item["quantity"]); } ?> <tr> <td colspan="2" align="right">Total:</td> <td align="right"><?php echo $total_quantity; ?></td> <td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td> <td></td> </tr> </tbody> </table> <?php } else { ?> <div class="no-records">Your Cart is Empty</div> <?php } ?> </div> </div> <br /><br /> <?php include 'footer_student.php'; ?> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery-3.4.1.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/popper.min.js"></script> <script src="js/bootstrap-4.4.1.js"></script> </body> </html>
How can I make index.php?view=cart work in place of cart.php in the following code? Works: header("Location: cart.php?msg=Thank you. Check your e-mail for Login details."); die; } else header("Location: cart.php?msg=Account with given email does not exist."); die; Doesn't work: header("Location: index.php?view=cart?msg=Thank you. Check your e-mail for Login details."); die; } else header("Location: index.php?view=cart?msg=Account with given email does not exist."); die; Hi. I have just one question (I have searched for an answer for this but have not been able to locate one): How do you go about changing the text on a "Submit Query" button to display simply "Submit"? Below is the current code for the page that displays said button. Thank-you in advance for any help or direction. <?php include 'connection.php'; $query = "SELECT * FROM people"; $result = mysql_query($query) or die(mysql_error()); while ($person = mysql_fetch_array($result)){ echo $person ['name']; echo $person ['descrip']; } ?> <H1>Add Your Review:</H1> <form action="create.php" method="post"> Subject <input type="text" name="inputName" value=""/> </br > Review <textarea cols="50" rows="4" name="inputDesc" value=""/></textarea> </br > <input type= "submit" name= "submit"/> </form> <html> <head></head> <body> <p>The current second is <span style='font-size:16px;font-weight:bold;color:red;position:absolute;right:25px;'><?php echo time(); ?></span> on this computer.</p> </body> </html> ok im making a shooping cart how do i make it so it remembers that items people add to the cart Hello, I got my hands in a php tutorial about creating a custom cart using only php. The thing is that, the code is working like that: 1. you see the items in the items.php page 2. you click on an item to open it in a new page and see full description 3. the add button is in the specific item's page and that's how the code works. Grabs the URL' s id variable and then get's processed. What I want: 1. To modify the code a little bit in order to have the add button into the into my items.php page so I skip the view full description link (I just don't like it as a requirement to add something to cart) But somewhere on my way there I got lost... Here are the codes (as they work in original script): For adding an item: Code: [Select] if (isset($_POST['pid'])) { $pid = $_POST['pid']; $wasFound = false; $i = 0; // If the cart session variable is not set or cart array is empty if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { // RUN IF THE CART IS EMPTY OR NOT SET $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1)); } else { // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT foreach ($_SESSION["cart_array"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $pid) { // That item is in cart already so let's adjust its quantity using array_splice() array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1))); $wasFound = true; } // close if condition } // close while loop } // close foreach loop if ($wasFound == false) { array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1)); } } header("location: ../p_cart.php"); exit(); }The check URL variable & the Add Button (both at the same page) the link of "View All Details" looks like this in order for this to work: <a href="specitem.php?id=1"> so it grubs the URL' s id and executes the code (something that I don't want) I want to take the id from my item form. Code: [Select] <?php // Check to see the URL variable is set and that it exists in the database if (isset($_GET['id'])) { // Connect to the MySQL database include "storescripts/connect_to_mysql.php"; $id = preg_replace('#[^0-9]#i', '', $_GET['id']); // Use this var to check to see if this ID exists, if yes then get the product // details, if no then exit this script and give message why $sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); $productCount = mysql_num_rows($sql); // count the output amount if ($productCount > 0) { // get all the product details while($row = mysql_fetch_array($sql)){ $product_name = $row["product_name"]; $price = $row["price"]; $details = $row["details"]; $category = $row["category"]; $subcategory = $row["subcategory"]; $date_added = strftime("%b %d, %Y", strtotime($row["date_added"])); } } else { echo "That item does not exist."; exit(); } } else { echo "Data to render this page is missing."; exit(); } Code: [Select] <form id="form1" name="form1" method="post" action="cart.php"> <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /> <input type="submit" name="button" id="button" value="Add to Shopping Cart" /> </form> Hello everyone I have coded a php cart for my website. I coded one myself instead of using a big box because it is a membership based sites where users use credits to order not cash. I have a 'Sizes' table with (size_id and size_name) and a 'Sizes_List' table with (size_id and product_id) which stores the size options of each product. It is displayed fine on the product page. Anyhoo. It works great.. there aren't any actual errors in the code but I am having trouble with 3 things.. 1. displaying the product size [i grab it in $_POST and add it to the cart_array) but it doesn't show up. 2. If I add another product, but a different size, to the cart it just changes the quantity of the product but doesn't add a new line. 3. I need to put items on "hold" for a certain amount of time (e.g. if you add a pair of True Religions in size 32 to your cart they are no longer available to anybody for 20 minutes and if you don't checkout they are back in the store). For the purpose of this question I have removed the need to be logged in for 1 product page and the cart. http://www.theskinnyminnie.com/user/rent/product.php?id=4/ <<product http://www.theskinnyminnie.com/user/mybox.php <<cart Here is the code it POST the values to the cart (if user adds to cart) Code: [Select] <div id="addproduct"><form id="form1" name="form1" method="post" action="../mybox.php"> <div id ="size">Size: <select name="size"> <?php echo $the_sizes;?> </select></div> <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /> <input type="submit" name="button" id="button" value="Add to Box" /> </form></div> Here is the code for the cart User adds to cart: Code: [Select] <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 1 (if user attempts to add something to the cart from the product page) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (!empty($_POST['form1'])) { $pid = $_POST['pid']; $asizeid = $_POST['size']; echo $asizeid; $wasFound = false; $i = 0; // If the cart session variable is not set or cart array is empty if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { // RUN IF THE CART IS EMPTY OR NOT SET $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1, "asize_id" => $asizeid)); } else { // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT foreach ($_SESSION["cart_array"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $pid) { // That item is in cart already so let's adjust its quantity using array_splice() array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1, "asize_id" => $asizeid))); $wasFound = true; } // close if condition } // close while loop } // close foreach loop if ($wasFound == false) { array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1, "asize_id" => $asizeid)); } } header("location: mybox.php"); exit(); } ?> User empties shopping car Code: [Select] <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 2 (if user chooses to empty their shopping cart) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") { unset($_SESSION["cart_array"]); } ?> <?php adjust item quantity Code: [Select] <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 3 (if user chooses to adjust item quantity) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") { // execute some code $item_to_adjust = $_POST['item_to_adjust']; $quantity = $_POST['quantity']; $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers if ($quantity >= 100) { $quantity = 99; } if ($quantity < 1) { $quantity = 1; } if ($quantity == "") { $quantity = 1; } $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $item_to_adjust) { // That item is in cart already so let's adjust its quantity using array_splice() array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity, "asize_id" => $asizeid))); } // close if condition } // close while loop } // close foreach loop } ?> remove item Code: [Select] <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 4 (if user wants to remove an item from cart) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") { // Access the array and run code to remove that array index $key_to_remove = $_POST['index_to_remove']; if (count($_SESSION["cart_array"]) <= 1) { unset($_SESSION["cart_array"]); } else { unset($_SESSION["cart_array"]["$key_to_remove"]); sort($_SESSION["cart_array"]); } } ?> View Cart - Ignore $orderSummary it is for the checkout process .. Code: [Select] <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 5 (render the cart for the user to view on the page) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $cartOutput = ""; $itemtotal = ""; $cartTotal = ""; $orderTotal = ""; $pp_checkout_btn = ''; $product_id_array = ''; if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { $itemtotal = "0"; $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2><br />"; } else { $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $item_id = $each_item['item_id']; $sql = mysql_query("SELECT * FROM Products WHERE product_id='$item_id' LIMIT 1"); while ($row = mysql_fetch_array($sql)) { $product_brand = $row["product_brand"]; $product_style = $row["product_style"]; $credits = $row["credits"]; $details = $row["details"]; } $sql4 = mysql_query("SELECT * FROM Sizes WHERE size_id = '$asize_id'"); while($name3 = mysql_fetch_array($sql4)){$product_size = $name3['size_name'];} $creditstotal = $credits * $each_item['quantity']; $cartTotal = $creditstotal + $cartTotal; $orderTotal = $creditstotal + $orderTotal; $itemtotal += $each_item['quantity']; $orderItem_qty = $each_item["quantity"]; $orderItem_total += $each_item["quantity"]; $orderSummary .= "<tr>"; $orderSummary .= "<td>"; $orderSummary .= "<div class = 'an_order_item'>"; $orderSummary .= "<img class ='an_order_img' src = 'inventory_images/".$item_id.".jpg' />"; $orderSummary .= "<div class = 'an_order_box'>"; $orderSummary .= "<div class = 'an_order_title'>"; $orderSummary .= "<h1>".$product_brand." - <font color='black'>".$product_style. "</font></h1>"; $orderSummary .= "</div>"; $orderSummary .= "<div class = 'an_order_size'>"; $orderSummary .= "<h1>Size - ".$product_size."</h1>"; $orderSummary .= "</div>"; $orderSummary .= "<div class = 'an_ordercalc'>"; $orderSummary .= "<h1>".$orderItem_qty." x ".$credits."pts = ".$creditstotal."pts</h1>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</td>"; $orderSummary .= "</tr>"; $orderSummary2 .= "<tr>"; $orderSummary2 .= "<td>"; $orderSummary2 .= "<div class = 'an_order_item'>"; $orderSummary2 .= "<img class ='an_order_img' src = 'rent/inventory_images/".$item_id.".jpg' />"; $orderSummary2 .= "<div class = 'an_order_box'>"; $orderSummary2 .= "<div class = 'an_order_title'>"; $orderSummary2 .= "<h1>".$product_brand."</h1>"; $orderSummary2 .= "<h1><font color='black'>".$product_style. "</font></h1>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</td>"; $orderSummary2 .= "</tr>"; $x = $i + 1; $product_id_array .= "$item_id-".$each_item['quantity'].","; // Dynamic table row assembly $cartOutput .= "<tr>"; $cartOutput .= $sizeid; $cartOutput .= '<td class="img"><a href="rent/product.php?id=' . $item_id . '"><img src="rent/inventory_images/' . $item_id . '.jpg" alt="' . $product_brand. '" height="121px" border="1" /></a><br /></td>'; $cartOutput .= '<td class="desc"> <strong><a href="rent/product.php?id=' . $item_id . '">' . $product_brand."-".$product_style . '</a></strong><ul class="attributes"><li>'. $details .'</li></ul><p class="size">Size - '.$product_size.'</p></td>'; $cartOutput .= '<td class="price">' . $credits .' <font id="pts">PTS</font></td>'; $cartOutput .= '<td class="qty"><form action="mybox.php" method="post"> <input name="quantity" type="number" value="' . $each_item['quantity'] . '" size="1" maxlength="2" /> <input class="change" name="adjustBtn' . $item_id . '" type="submit" value="Update" /> <input name="item_to_adjust" type="hidden" value="' . $item_id . '" /> </form> <form action="mybox.php" method="post"><input class="delete" name="deleteBtn' . $item_id . '" type="submit" value="Remove" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form> </td>'; //$cartOutput .= '<td>' . $each_item['quantity'] . '</td>'; $cartOutput .= '<td class="total">' . $creditstotal .'</td>'; $cartOutput .= '</tr>'; $i++; } setlocale(LC_MONETARY, "en_US"); //$cartTotal = $cartTotal.''; $cartTotal = '<tr><td colspan="4">Total</td><td class="total cart-total-price">' . $cartTotal .'</td></tr>'; // Finish the Paypal Checkout Btn } ?> I have followed a shopping cart tutorial from this website. http://v3.thewatchmakerproject.com/journal/276/ 1. When you refresh the page it adds another item to the cart. 2. I would like to add an image of the products from a folder and the link of the images in the database. Can some one please help. Urgently! Thanks. I have a form which gets filled in with values from a session array. This form also has just one update button. If I have 3 items in my cart and I want to update just one of the items how would I pass the id of that product to my cart class? The problem I'm having is the id of the last product in the cart is passed so the update never works unless its the last item thats being updated. If I was to wrap each item in a form with an add update button it will work the way I want it to work but I really dont want to add extra buttons. Is there anyway to to wrap all the items in one form and get just the input values of the item whos quantity is being changed. Here is the cart form: Code: [Select] <form action="index.php?view=update_cart" method="post" > <table id="items"> <thead> <tr> <th>Item</th> <th>Item Price</th> <th>Qty</th> <th>Subtotal</th> <!-- <th>Edit</th>--> </tr> </thead> <tbody> <?php foreach($cart->Cart() as $item):?> <!--<form action="index.php?view=update_cart" method="post" >--> <input type="hidden" id="prodId" name="prodId" value="<?php echo $item['Id']; ?>" /> <tr> <td><?php echo $item['Product']; ?></td> <td><?php echo '$'.$item['Price']; ?></td> <td><input type="text" size="2" name="qty" maxlength="2" value="<?php echo $item['Quantity']; ?>" onsubmit="this.value"/></td> <td><?php echo '$'.number_format($item['Price']*$item['Quantity'],2); ?></td> <!--td><input type="submit" name="update" value="Update" /></td--> </tr> <!--</form>--> <?php endforeach; ?> </tbody> </table> <p><input type="submit" name="update" value="Update" /></p> </form> When I debug my code and hover over the $_POST['prodId'] i will see the id of the last product. Any help will be appricated thanks. everything seems to b working correctly...except 'update cart' where if i click on update cart button it redirects me to d previous page...instead of calculating the input.. i m not able 2 figure out what d problem is.. here's d 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 ) { ?> <form action="<?php echo $_SERVER['PHP_SELF'] .'?action=update'; ?>" method="POST" name="frmCart" id="frmCart"> <table width="780" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable"> <tr class="entryTableHeader"> <td colspan="2" align="center">Item</td> <td align="center">Unit Price</td> <td width="75" align="center">Quantity</td> <td align="center">Total</td> <td width="75" align="center"> </td> </tr> <?php $subTotal = 0; for ($i = 0; $i < $numItem; $i++) { extract($cartContent[$i]); $productUrl = "index.php?c=$cat_id&p=$pd_id"; $subTotal += $pd_price * $ct_qty; ?> <tr class="content"> <td width="80" align="center"><a href="<?php echo $productUrl; ?>"><img src="<?php echo $pd_thumbnail; ?>" border="0"></a></td> <td><a href="<?php echo $productUrl; ?>"><?php echo $pd_name; ?></a></td> <td align="right"><?php echo displayAmount($pd_price); ?></td> <td width="75"><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 align="right"><?php echo displayAmount($pd_price * $ct_qty); ?></td> <td width="75" align="center"> <input name="btnDelete" type="button" id="btnDelete" value="Delete" onClick="window.location.href='<?php echo $_SERVER['PHP_SELF'] . "?action=delete&cid=$ct_id"; ?>';" class="box"> </td> </tr> <?php } ?> <tr class="content"> <td colspan="4" align="right">Sub-total</td> <td align="right"><?php echo displayAmount($subTotal); ?></td> <td width="75" align="center"> </td> </tr> <tr class="content"> <td colspan="4" align="right">Shipping </td> <td align="right"><?php echo displayAmount($shopConfig['shippingCost']); ?></td> <td width="75" align="center"> </td> </tr> <tr class="content"> <td colspan="4" align="right">Total </td> <td align="right"><?php echo displayAmount($subTotal + $shopConfig['shippingCost']); ?></td> <td width="75" align="center"> </td> </tr> <tr class="content"> <td colspan="5" align="right"> </td> <td width="75" align="center"> <input name="btnUpdate" type="submit" id="btnUpdate" value="Update Cart" class="box"></td> </tr> </table> </form> <?php } else { ?> <p> </p><table width="550" border="0" align="center" cellpadding="10" cellspacing="0"> <tr> <td><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></td> </tr> </table> <?php } $shoppingReturnUrl = isset($_SESSION['shop_return_url']) ? $_SESSION['shop_return_url'] : 'index.php'; ?> <table width="550" border="0" align="center" cellpadding="10" cellspacing="0"> <tr align="center"> <td><input name="btnContinue" type="button" id="btnContinue" value="<< Continue Shopping" onClick="window.location.href='<?php echo $shoppingReturnUrl; ?>';" class="box"></td> <?php if ($numItem > 0) { ?> <td><input name="btnCheckout" type="button" id="btnCheckout" value="Proceed To Checkout >>" onClick="window.location.href='checkout.php?step=1';" class="box"></td> <?php } ?> </tr> </table> <?php require_once 'include/footer.php'; ?> and here is update cart function: function updateCart() { $cartId = $_POST['hidCartId']; $productId = $_POST['hidProductId']; $itemQty = $_POST['txtQty']; $numItem = count($itemQty); $numDeleted = 0; $notice = ''; for ($i = 0; $i < $numItem; $i++) { $newQty = (int)$itemQty[$i]; if ($newQty < 1) { // remove this item from shopping cart deleteFromCart($cartId[$i]); $numDeleted += 1; } else { // check current stock $sql = "SELECT pd_name, pd_qty FROM tbl_product WHERE pd_id = {$productId[$i]}"; $result = dbQuery($sql); $row = dbFetchAssoc($result); if ($newQty > $row['pd_qty']) { // we only have this much in stock $newQty = $row['pd_qty']; // if the customer put more than // we have in stock, give a notice if ($row['pd_qty'] > 0) { setError('The quantity you have requested is more than we currently have in stock. The number available is indicated in the "Quantity" box. '); } else { // the product is no longer in stock setError('Sorry, but the product you want (' . $row['pd_name'] . ') is no longer in stock'); // remove this item from shopping cart deleteFromCart($cartId[$i]); $numDeleted += 1; } } // update product quantity $sql = "UPDATE tbl_cart SET ct_qty = $newQty WHERE ct_id = {$cartId[$i]}"; dbQuery($sql); } } if ($numDeleted == $numItem) { // if all item deleted return to the last page that // the customer visited before going to shopping cart header("Location: $returnUrl" . $_SESSION['shop_return_url']); } else { header('Location: cart.php'); } exit; } Can someone give me name of free shopping cart with auctions(offers) like Open Classifieds ? Hello, I'm trying to implement a function called 'delete_cart' but I can't seem to get it working. Here's the function code: Code: [Select] function delete_cart(){ unset($_SESSION['cart']); } Here's the HTML / php code: Code: [Select] if (!empty($_SESSION['cart'])) { echo '<a href="index.php?p=cart?delete_cart=true">delete cart</a> '; } When you click on 'delete cart', the page just refreshes to the home page and I am able to re-visit that same cart with the same items in. I've also noticed when I log out, the shopping cart is deleted. Hey all not been on here for a few years, been out of work. i am back and throwing ,myself straight into the deep end. Is it hard to integrate a shopping cart into a website. Any good example snippets of code to look at? I have a little search but someone always seems to know a better one. Why are almost all tutorials these days you have to pay for (times are getting hard ). hello all, hoping someone can help, i am still pretty new to php and i am stuck on creating a php cart. the code i have below is working, but the problem i am having is i need a store in the session array i am struggling to get my head around it so hoping someone can help here. i am hoping to have $product_id (which is currently in) $option1,2,3 and $text (for a textarea box) heres my function file function get_product() { echo "Hello"; } function add_product() { $product_id = $_POST['product_id']; if ($product_id == 'NULL') { echo "No Product Selected!"; } if (isset($_SESSION['cart'][$product_id])) { $_SESSION['cart'][$product_id]++; echo "<script>window.location='product.php'</script>"; }else{ $_SESSION['cart'][$product_id] = 1; echo "<script>window.location='product.php'</script>"; } } function increase_product() { $product_id = $_GET['product_id']; $_SESSION['cart'][$product_id]++; echo "<script>window.location='cart.php'</script>"; } function decrease_product() { $product_id = $_GET['product_id']; $_SESSION['cart'][$product_id]--; echo "<script>window.location='cart.php'</script>"; } function empty_cart() { unset($_SESSION['cart']); echo "<script>window.location='cart.php'</script>"; } }() my product page (currently with out the extra form items (option1,2,3 etc) include '_class/cart.php';$core->session($mode = 'start');if(isset($_POST['buy'])){$cart->add_product();}?><!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>Product</title></head><body><?php $core->navbar();?><form method="post" action=""><input name="product_id" type="hidden" value="Coffee" /><h1>Cup Of Coffee</h1><p>Buy me you know you want too!</p><input name="buy" type="submit" value="Add To Basket" id="buy" /></form><form method="post" action=""><input name="product_id" type="hidden" value="Biscuits" /><h1>Barrel Of Biscuits</h1><p>When Coffee Just Gives You The Munchies!</p><input name="buy" type="submit" value="Add To Basket" id="buy" /></form></body></html>() my include cart file if (isset($_SESSION['cart'])) {//Session Cart foreach($_SESSION['cart'] as $product_id => $quantity){//Session Array if($quantity < 1){//Quantity Less Then 1 unset($_SESSION['cart'][$product_id]); echo "<script>window.location='cart.php'</script>"; }//End Quantity Less Then 1 if(!$_SESSION['cart']){//Cart Array Empty unset($_SESSION['cart']); echo "<script>window.location='cart.php'</script>"; }//End Cart Array Empty if ($product_id != NULL){//Show Products echo '<h1>' . $product_id . '</h1>'; echo "Quantity <br>"; ?><a href="cart.php?product_id=<?php echo $product_id; ?>&option=increase">+</a> <?php echo $quantity; ?> <a href="cart.php?product_id=<?php echo $product_id; ?>&option=decrease">-</a><?php }//End Show Products }//End Session Array require 'library/paypal.php'; }else{ echo "Your Basket Is Empty"; }//End Session Cart() and my actual cart file include '_class/cart.php';$core->session($mode = 'start');?><!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>Cart</title></head><body><?php$core->navbar(); if (isset($_GET['product_id']['option'])) { $product_id = $_GET['product_id']; $option = $_GET['option']; if ($option == 'decrease'){ $cart->decrease_product(); } if ($option == 'increase'){ $cart->increase_product(); } }elseif (isset($_GET['option'])){ $option = $_GET['option']; if ($option == 'empty'){ $cart->empty_cart(); } }else{ require 'library/cart.php'; }?><p><a href="cart.php?option=empty">Empty Cart</a></p></body></html>() please explain answers or exmples as clear as possible thanks everyone i make a shopping cart,but it dont show the product i have choose. it suppose to show the product i choose at the cart table but its still show the "Your Cart is empty" result..im still new.i follow the instruction from the youtube.sorry for my bad english.
here is the index2.php code
<? session_start(); require("connection.php"); if(isset($_GET['page'])){ $pages=array("products", "cart"); if(in_array($_GET['page'], $pages)) { $_page=$_GET['page']; }else{ $_page="products"; } }else{ $_page="products"; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> <body> </body> </html> <link rel="stylesheet" href="style2.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { }); </script> </head> <body> <div id="container"> <div id="main"> <?php require($_page.".php"); ?> </div> <div id="sidebar"> <h1>Cart</h1> <?php if(isset($_SESSION['cart'])){ $sql="SELECT * FROM products WHERE id_product IN ("; foreach($_SESSION['cart'] as $id => $value) { $sql.=$id.","; } $sql=substr($sql, 0, -1).") ORDER BY name ASC"; $query=mysql_query($sql); while($row=mysql_fetch_array($query)){ ?> <p><?php echo $row['name'] ?> x <?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?></p> <?php } }else{ echo "<p>Your Cart is empty</p>"; } ?> </div> </div> </body>and this is the products.php code <?php if(isset($_GET['action']) && $_GET['action']=="add"){ $id=intval($_GET['id']); if(isset($_SESSION['cart'][$id])){ $_SESSION['cart'][$id]['quantity']++; }else{ $sql_s="SELECT * FROM products WHERE id_product={$id}"; $query_s=mysql_query($sql_s); if(mysql_num_rows($query_s)!=0){ $row_s=mysql_fetch_array($query_s); $_SESSION['cart'][$row_s['id_product']]=array( "quantity" => 1, "price" => $row_s['price'] ); }else{ $message="This product id it's invalid!"; } } } ?> <h1>Product List</h1> <?php if(isset($message)){ echo "<h2>$message</h2>"; } ?> <table> <tr> <th>Name</th> <th>Description</th> <th>Price</th> <th>Action</th> </tr> <?php $sql="SELECT * FROM products ORDER BY name ASC"; $query=mysql_query($sql); while ($row=mysql_fetch_array($query)) { ?> <tr> <td><?php echo $row['name'] ?></td> <td><?php echo $row['description'] ?></td> <td><?php echo $row['price'] ?></td> <td><a href="index2.php?page=products&action=add$id=<?php echo $row['id_product'] ?>">Add To Cart</a></td> </tr> <?php } ?> </table> hi all i have a simple shopping cart up and runniing i just cannot think of how to remove all items within the cart i can do a remove one item easily but how woudl i remove all items inmy cart ? Would i delete the cookie id or ? Hi All I have my shopping cart working correctly, just a small tweak which i would like to make to it. Here is the code i currently use... Code: [Select] echo '<p>' . $fldname . ' <a href="cart.php?action=add&id=' . $row['idinfo'] . '">Add to report</a></p>'; But i want it so that when i click 'Add to report' is does not take me to cart.php, but it still adds the item into the shopping cart. kind of just refeshs the current page? Im sure it is only a small tweak which needs to be done.. Any help would be great -Dream |