Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

php issues

hi everybody i have a problem in fixing the cart quantity and total cost on header.php

when the user change the number in the input field inside cart.php , the according detail on the

header does not change accordingly, dont know if it is due to header.php is included by cart at the

top of the page, so when those code in cart.php run, the header cannot get the changes.

*****   header.php  *******
<?php
session_start();
error_reporting(0);

if (isset($_SESSION['quantity'])) {
    $new_quantity = $_SESSION['quantity'];
}

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minutes ago
    session_unset(); // unset $_SESSION variable for the run-time 
    session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
<!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=windows-1252" />
<title>Pet Shop</title>

<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/hoverIntent.js"></script>
<script type="text/javascript" src="js/superfish.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="superfish.css" />

<script type="text/javascript">
$(function(){
    jQuery('#example').superfish({
        delay: 500,
        animation: {opacity:'show',height:'show'},
        animationOut:  {opacity:'hide',height:'hide'},
        speed:         'fast',          
        speedOut:      'normal' 
    });
});
</script>
</head>
<body>

<div id="wrap">
    <div class="header">
        <div class="logo">
            <a href="index.html"><img src="images/logo.gif" alt="" title="" border="0" /></a>
        </div>   
        <div class="cart_top">
            <div class="title"><span class="title_icon"><img src="images/cart.gif" alt="" title="" style="padding-top:4px;"/></span></div>
            <div class="home_cart_content_top">
            <?php
echo $_SESSION['quantity'];
?> x items | <span style="color:#000000">TOTAL: $<?php
echo $_SESSION['total'];
?></span>
            </div>
            <a href="cart.php" class="view_cart" style="color:#000000">view cart</a>
        </div>







***************** cart.php *********************

<?php
include 'top_section.php';
?>
<?php
include 'header.php';
?>

<?php
error_reporting(0);
?>
<?php
if (!isset($_SESSION['user_name'])) {
    redirect('index.php');
}

?>

 <div id="menu">
            <ul class="sf-menu" id="example">
                <li>
                    <a href="index.php">home</a>
                </li>
                <li>
                    <li><a href="about.php">about us</a></li>
                </li>
                <li>
                    <a href="category_main.php">category</a>
                    <ul class="category_submenu">
                        <?php
$sql    = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($result)) {
    echo '<li><a href="category.php?cat_id=' . $rows['catid'] . '">' . $rows['name'] . '</a></li>';
}
?>        

                    </ul>
                </li>
                <li><a href="specials.php">specials pets</a></li>
                <?php
if (isset($_SESSION['uid'])) {
    echo '';
} else {
    echo '<li><a href="myaccount.php">my account</a></li>';
}
?>
               <li><a href="register.php">register</a></li>
                <li><a href="contact.php">contact</a></li>
                <?php
if (isset($_SESSION['uid'])) {
    echo '<li><a href="logout.php">Logout</a></li>';
}
?>    
            </ul>
        </div>     
    </div> 



       <div class="center_content" style="background:none">
           <div class="left_content">



        <!-- start of cart content -->
            <div class="breadcrumb sub">
                <?php
include 'breadcrumb.php';
?>
           </div>

            <div class="feat_prod_box_details">



            <!-- start of cart -->
            <?php

$product_id  = $_GET['id']; //the product id from the URL 
$category_id = $_GET['catid'];
$action      = $_GET['action']; //the action from the URL 




//if there is an product_id and that product_id doesn't exist display an error message
if ($product_id && !productExists($product_id, $conn)) {
    die("Error. Product Doesn't Exist");
}

switch ($action) { //decide what to do    

    case "add":
        $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id 
        break;

    case "remove":
        if ($_SESSION['cart'][$product_id] > 0) {
            $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
        }
        if ($_SESSION['cart'][$product_id] == 0)
            unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. 
        break;

    case "add_multi":
        if ($_POST['qtn_submit']) {
            $_SESSION['cart'][$product_id] = $_POST['qtn'];
        }
        break;

    case "remove_all":
        $_SESSION['cart'][$product_id] = 0;
        break;

    case "empty":
        unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
        break;

}


if (!$_SESSION['cart']) {
    $_SESSION['cart'] = array();
}
if ($_SESSION['cart']) { //if the cart isn't empty
    //show the cart

    echo "<table class=\"member_table\" border=\"1\" padding=\"3\" width=\"100%\">"; //format the cart using a HTML table
    echo "<tr>";
    echo "<td>Product Name:</td>";
    echo "<td>Product image:</td>";
    echo "<td style='width:60%'>Quantity</td>";
    echo "<td>Product price total</td>";
    echo "</tr>";
    //iterate through the cart, the $product_id is the key and $quantity is the value
    foreach ($_SESSION['cart'] as $product_id => $quantity) {

        //get the name, description and price from the database - this will depend on your database implementation.
        //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
        $sql      = sprintf("SELECT name, description, unit_price FROM products WHERE pid = %d;", $product_id);
        //part of getting image from sql table    
        $sql_2    = "SELECT * FROM photos WHERE pid = $product_id";
        $result   = mysqli_query($conn, $sql);
        $result_2 = mysqli_query($conn, $sql_2);
        $rows     = mysqli_fetch_array($result, MYSQL_NUM);
        $rows2    = mysqli_fetch_array($result_2, MYSQL_NUM);
        //Only display the row if there is a product (though there should always be as we have already checked)
        if (count($rows) > 0) {

            list($name, $description, $price) = $rows;

            $line_cost = $price * $quantity; //work out the line cost
            $total += $line_cost; //add to the total cost

            echo "<tr>";
            //show this information in table cells
            echo "<td align=\"center\">$name</td>";
            echo '<td align="center"><img src="images/' . $rows2['file'] . '" /></td>';
            //along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
            echo "<td align=\"center\"><form name=\"qtn_num\" method=\"post\"><input type=\"text\" name=\"qtn\" size=\"3\" value=\"$quantity\" /><a href=\"$_SERVER[PHP_SELF]?action=add_multi&id=$product_id\"><input type=\"submit\" value=\"submit\" name=\"qtn_submit\"/></a></form><a href=\"$_SERVER[PHP_SELF]?action=remove&id=$product_id\" class=\"remove_link\">Remove one item</a><a href=\"$_SERVER[PHP_SELF]?action=remove_all&id=$product_id\" class=\"remove_link\">Remove all</a></td>";
            echo "<td align=\"center\">$line_cost</td>";

            echo "</tr>";

        }

    }
    $_SESSION['product_name'] = array();
    $_SESSION['quantity']     = array();
    $_SESSION['total']        = array();

    $_SESSION['product_name'] = $name;

    $_SESSION['quantity'] = $quantity;

    $_SESSION['total'] = $total;


    //show the total
    echo "<tr>";
    echo "<td colspan=\"2\" align=\"right\">Total</td>";
    echo "<td colspan=\"2\" align=\"right\">$total</td>";
    echo "</tr>";

    //show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
    echo "<tr>";
    echo "<td colspan=\"4\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>";
    echo "</tr>";
    echo "</table>";



} else {
    //otherwise tell the user they have no items in their cart
    echo "You have no items in your shopping cart.";

}

//function to check if a product exists
function productExists($product_id, $conn)
{
    //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
    $sql = "SELECT * FROM products WHERE pid = '$product_id'";

    $result = mysqli_query($conn, $sql);
    $rows   = mysqli_fetch_assoc($result);

    return count($rows) > 0;
}

?>
           <div class="f_clear"></div>
            <div class="cart_btn_nav">
                <a href="category_main.php" class="continue f_left">Continue Shopping</a>
                <!-- end of cart -->

                <a href="order_form.php" class="checkout f_right">checkout &gt;</a>
            </div>


















            </div>    
         <!-- end of cart content -->   





        <div class="clear"></div>
        </div><!--end of left content-->






       <div class="clear"></div>
       </div><!--end of center content-->


       <?php
include 'footer.php';
?>

2 Answers

  • The easy way (wrong way) is refresh all the page.

A good idea is "update" the value in the header file via jQuery, change this in your header.php.

<span class="label_quantity"><?php echo $_SESSION['quantity']; ?></span> x items | <span style="color:#000000" class="label_total">TOTAL: $<?php echo $_SESSION['total']; ?>

The jQuery code:

<script type="text/javascript">
   $(document).ready(function () {
       $('#input').keyup(function () { 
          $('.label_quantity').html($(this).val());
       });
   });
</script>

With this, you can "update" the quantity, the next step could be update the $_SESSION, you can try to call via ajax an external file when the $_SESSION is updated with the new value in the text box.

If you need more help or ideas reply :)

thx nice and detail