Hi guys good day, im a student and i want to practice my php skills, i have a big problem in arrays that i cant solve almost a week so i decided to attach the php files as well as its database.pls help me so that i can study this later.

there are 3 most important forms in my php files.
1. index.php
2.product.php
3. cart.php

Here is my screenshot of what i want to do in cart.php. i want to include the unit price and the sumofprice in my array as indicated in my screenshot so that i can include this information in a session variable later on.

My screenshot

My php Files

Here is the code of three forms as requested:

cart.php

<?php ob_start(); ?>
<?php session_start();?>
<?php include("includes/functions.php");?>
<?php error_rep(); ?>
<?php require_once("includes/connection.php");?>

<?php 

//Section 1 (if user attempts to add something to the cart from the product page)
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));
       }
  }

  redirect_to("cart.php"); 
    exit();
}
?>
<?php 

// Section 2 (if user chooses to empty their shopping cart)
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
    unset($_SESSION["cart_array"]);

}
?>

<?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))); 
          } // close if condition
          } // close while loop
  } // close foreach loop
}

?>
<?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"]);
  }
}
?>
<?php //     Section 5  (render the cart for the user to view on the page)

$pp_checkout_btn ="";
$cartOutput = "";
$cartTotal = "";
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
    $i = 0;
  foreach ($_SESSION["cart_array"] as $each_item) { 
    $item_id = $each_item['item_id'];

    $sql = mysql_query("SELECT * FROM product WHERE id='$item_id' LIMIT 1");
    while ($row = mysql_fetch_array($sql)) {
      $product_name = $row["name"];
      $price = $row["price"];
      $details = $row["details"];
    }
    //$_SESSION["cart_array"][0]['pricetotal'] = $pricetotal = $price * $each_item['quantity'];

    $pricetotal = $price * $each_item['quantity'];
    $cartTotal = $pricetotal + $cartTotal;

    echo $price ."<br/>";
    echo $pricetotal ;

        $pricetotal = number_format($pricetotal,2);

    // Dynamic Checkout Btn Assembly

    $x = $i + 1;
  $pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">

        <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
        <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">  ';
    // Create the product array variable
    // Dynamic table row assembly
    $cartOutput .= "<tr>";
    $cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' 
          . $product_name . '</a><br />
      <img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name. '" width="40" height="52" border="1" /></td>';
    $cartOutput .= '<td>' . $details . '</td>';
    $cartOutput .= '<td>Php ' . $price . '</td>';
    $cartOutput .= '<td><form action="cart.php" method="post">
    <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
    <input name="adjustBtn' . $item_id . '" type="submit" value="Update" />
    <input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
    </form></td>';
    //$cartOutput .= '<td>' . $each_item['quantity'] . '</td>';
    $cartOutput .= '<td>' . $pricetotal . '</td>';
    $cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" />
    <input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>';
  // $cartOutput .= '<td>' . $size . '</td>'; //experiment
    $cartOutput .= '</tr>';
    $i++; 
    } 

   $productItems = $_SESSION["cart_array"] ; //
        foreach($productItems as $key => $productItem){
        $newIndex = $key + 1;

      }  
    $productItems[$newIndex]['pricetotal']  =  $cartTotal ; //

      $cartTotal = number_format($cartTotal,2);
      $cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." Php</div>";

  }

?>

<!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>Your Cart</title>
</head>
<body>
<div id="wrapper">
    <?php include("includes/header.php"); ?>
     <div id="mainMenu">
            <!-- Start css3menu.com BODY section id=1 -->
            <ul id="css3menu1" class="topmenu">
                <li class="topfirst"><a href="#" style="height:18px;line-height:18px;">Dashboard</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">order</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">Customer</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">Inventory</a></li>
                <li class="toplast"><a href="#" style="height:18px;line-height:18px;">Report</a></li>
            </ul>
            <p style="display:none"><a href="http://css3menu.com/">Easy CSS Drop Down Menu Css3Menu.com</a></p>
            <!-- End css3menu.com BODY section -->   
        </div> <!-- end of mainmenu -->
<div id="Buttons">
<a href = "index.php">Continue shopping </a><br/>
<a href = "delivery_details.php">Checkout </a>
</div> <!--buttons -->

    <div id="pageContent" style="margin:24px; text-align:left;">

    <br />
    <table width="100%" border="1" cellspacing="0" cellpadding="6">
      <tr>
            <td width="18%" bgcolor="#C5DFFA"><strong>Product</strong></td>
            <td width="45%" bgcolor="#C5DFFA"><strong>Product Description</strong></td>

            <td width="10%" bgcolor="#C5DFFA"><strong>Unit Price</strong></td>
            <td width="9%" bgcolor="#C5DFFA"><strong>Quantity</strong></td>
            <td width="9%" bgcolor="#C5DFFA"><strong>Total</strong></td>
            <td width="9%" bgcolor="#C5DFFA"><strong>Remove</strong></td>
             <td width="45%" bgcolor="#C5DFFA"><strong>size</strong></td>
      </tr>
     <?php echo $cartOutput; ?>

    </table>
    <?php echo $cartTotal; ?>
    <br />
<br />
    <br />
    <br />
    <a href="cart.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a>
    </div><!-- End of pageContent -->
   <br />


<?php 



echo "<br/>";

// $_SESSION['newProductItems'] = $productItems;


    foreach($productItems as $key => $item) {
    if(isset($result[$key])) {
    $productItems[$key]['price'] = $result[$key];
    }
    }

echo "<pre>";
print_r($productItems);
echo "</pre>";

  ?>
<?php include("includes/footer.php");  ?>
<?php ob_flush(); ?>
</div> <!--end of mainWrapper -->
</body>
</html>

product.php

<?php include("includes/functions.php");?>
<?php error_rep(); ?>
<?php require_once("includes/connection.php"); ?>

<?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  
    $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 product 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["name"];
             $price = $row["price"];
             $details = $row["details"];
             $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();
}
mysql_close();
?>

<!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=iso-8859-1" />
<title><?php echo $product_name; ?></title>
<style type="text/css">
<!--
.style1 {font-size: 10px}
-->
</style></head>
<link rel="stylesheet" href="stylesheet/style.css" type="text/css" media="screen" />
<body>
<div id="wrapper">
    <div id="header">
        <?php include("includes/header.php"); ?>

    </div> <!--end of header -->
    <div id="mainMenu">
            <!-- Start css3menu.com BODY section id=1 -->
            <ul id="css3menu1" class="topmenu">
                <li class="topfirst"><a href="#" style="height:18px;line-height:18px;">Dashboard</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">order</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">Customer</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">Inventory</a></li>
                <li class="toplast"><a href="#" style="height:18px;line-height:18px;">Report</a></li>
            </ul>
            <p style="display:none"><a href="http://css3menu.com/">Easy CSS Drop Down Menu Css3Menu.com</a></p>
            <!-- End css3menu.com BODY section -->   
        </div> <!-- end of mainmenu -->
  <p>
  </p>
  <div id="pageContent">
    <table width="979" height="5%" border="1" id="Content">
      <tr>
        <td width="234" height="239" valign="top"><div align="center">
        <img src="inventory_images/<?php echo $id; ?>.jpg" width="191" height="188" alt="<?php echo $product_name; ?>" /><br />

        <p align="center"><a href="inventory_images/<?php echo $id; ?>.jpg">View Full Size Image</a></p></td>

        <p>&nbsp;</p>
        <td width="729" height="239" valign="top"><p><?php echo $product_name; ?></p>
        <p><?php echo $price; ?></p>
        <p><?php echo $details; ?></p>
        <p>
        <form id="form1" name="form1" method="post" action="cart.php">
            <select name="size" id="size">
                <option selected="selected">Chooose size</option>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="30">30 </option>   
            </select>   
         <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /> 
        <input type="submit" name="button" id="button" value="Add to Shopping Cart" />

        </form>
        </p></td>
      </tr>
    </table>
        </div> <!--end of pageContent -->
     <?php include("includes/footer.php"); ?>
</div>  <!--end of wrapper -->
</body>
</html>

index.php

<?php include("includes/functions.php");?>
<?php require_once("includes/connection.php"); ?>
<?php error_rep(); ?>
<?php

// Run a select query to get my letest 6 items
$dynamicList = "";
$sql = get_product();                    
$productCount = mysql_num_rows($sql); // count the output amount
$dynamicList .= '<table width="105%"  cellpadding="6" class="product_holder"><tr>';
if ($productCount > 0) {
    while($row = mysql_fetch_array($sql)){ 
             $id = $row["id"];
             $product_name = $row["name"];
             $price = $row["price"];
             $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
             $dynamicList .= '<td width="124px" valign="top">
                              <a href="product.php?id=' . $id . '">
                              <img src="inventory_images/' . $id . '.jpg" 
                                    alt="' . $product_name . '" width="120" height="121" />
                              </a>
                              <br />' . $product_name . '<br />
                                    Php ' . $price . '<br />
                              <a href="product.php?id=' . $id . '">View Product Details</a></td>';
    }
    $dynamicList .= ' </tr></table>';
} else {
    $dynamicList = "We have no products listed in our store yet";
}
mysql_close();
?>

<br/>

<html>
<head> <title> Fiesta Store </title> </head>
<body>
    <div id="wrapper">   
    <?php include("includes/header.php"); ?>
     <div id="mainMenu">
            <!-- Start css3menu.com BODY section id=1 -->
            <ul id="css3menu1" class="topmenu">
                <li class="topfirst"><a href="#" style="height:18px;line-height:18px;">Dashboard</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">order</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">Customer</a></li>
                <li class="topmenu"><a href="#" style="height:18px;line-height:18px;">Inventory</a></li>
                <li class="toplast"><a href="#" style="height:18px;line-height:18px;">Report</a></li>
            </ul>
            <p style="display:none"><a href="http://css3menu.com/">Easy CSS Drop Down Menu Css3Menu.com</a></p>
            <!-- End css3menu.com BODY section -->   
        </div> <!-- end of mainmenu -->


    <div id="leftContent">         
    <table width="995" height="428" border="1">
    <tr>
             <td width="235" height="422" valign="top"><p><strong>Electronic commerce</strong>,commonly known as <strong>e-commerce</strong> or                                                                       <strong>e-comm</strong>, is the buying and selling of product or service over electronic systems   such as the Internet and other computer networks. Electronic commerce draws on such technologies as <a href="http://en.wikipedia.org/wiki/Electronic_funds_transfer" title="Electronic funds transfer">electronic funds transfer</a>, <a href="http://en.wikipedia.org/wiki/Supply_chain_management" title="Supply chain management">supply chain management</a>, <a href="http://en.wikipedia.org/wiki/Internet_marketing" title="Internet marketing">Internet marketing</a>, <a href="http://en.wikipedia.org/wiki/Online_transaction_processing" title="Online transaction processing">online transaction processing</a>, <a href="http://en.wikipedia.org/wiki/Electronic_data_interchange" title="Electronic data interchange">electronic data interchange</a> (EDI), <a href="http://en.wikipedia.org/wiki/Inventory_management_systems" title="Inventory management systems">inventory management systems</a>, and automated <a href="http://en.wikipedia.org/wiki/Data_collection" title="Data collection">data collection</a> systems. Modern electronic commerce typically uses the World Wide Web   at least at one point in the transaction's life-cycle, although it may   encompass a wider range.
    </p>
</div>   <!--end of leftContent--> 
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p></td>
<td width="468" valign="top"><p>Newest Items</p>
<p><?php echo $dynamicList ?></p>
</td>
<td width="200" valign="top">


    <form id="form1" name="form1" method="post" action="storeadmin/admin_login.php">
    <p align="center">username:<input type="text" name="username" id="username" />
    </p>
    <p align="center">password:<input type="password" name="password" id="password" />
    </p>
    <p align="center">&nbsp;</p>
    </blockquote>
    <p align="center">
    <input type="submit" name="log_in" id="log_in" value="Log in" />
    </p>
    </form>          
    </p></td>
    </tr>
    </table>
    <?php include("includes/footer.php"); ?>
    </div> <!--end of wrapper-->
</body>
</html>

Recommended Answers

All 4 Replies

Please just post your PHP inline here on the forum. Most of us don't like clicking links and downloading files.

array masters,, please help me to solve this :(

Member Avatar for diafol

400 lines of code. You're serious, right? Could you not cut out the irrelevant bits and concentrate on the php that's giving problems?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.