TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Custom Order Form (http://www.talkphp.com/absolute-beginners/5151-custom-order-form.html)

lashelles 12-06-2009 08:35 PM

Custom Order Form
 
Hey I've been working about a week on this script but I just can't seem to get it right. I'm trying to build an order form where users are presented with a list (drawn from a mysql relation) of available colors of paint shown in an HTML table. In every <tr> there is one <td> with an text input allowing users to choose their quantity. At the bottom of the form I'd like an add to cart button which stores the items (as well as session_id) into the 'cart' table in my database.

Some of the features I'm hoping for include:

Updating existing quantities if product is already in cart.

If one or more of the posted quantities is higher than the amount in stock, don't add anything to the cart and instead display the page again with an error message detailing which paints exceeded the available stock

If there are no errors display message that items have been added to cart


Some of my main issues include:


I have been doing everything from the same loop and I need to use the loop in areas that are not inside the table.. but as soon as I add another extract() or mysql_fetch_array things go crazy.

I'm not confident at all in what I'm doing



If anybody can help me it would be appreciated.. I've been pulling my hair out over this.


Here is what I've got so far (it's a mess)

PHP Code:

<?php

session_start
();

require_once 
'lib/database.php';

?>

<head>
<link rel="stylesheet" type="text/css" media="screen" href="include/screen.css">
</head>

<form action="<?php echo $_SERVER['PHP_SELF'?>" method="post">
<table id="colorchart" cellpadding="0" cellspacing="0">
<tr style="background:#CCCCCC;">
    <th>No.</th>
    <th>Color</th>
    <th>Series</th>
    <th>Size</th>
    <th>&nbsp</th>
    <th>Price</th>
    <th>Avail.</th>
    <th style="text-align:right; padding-right:25px;">Qty.</th>
</tr>

<?php

$query 
"SELECT mc.color_no, mc.color_name, mc.hex, mc.font, mc.series, pd.size, pd.retail, pd.price, pd.qty, pd.item_no
          FROM product pd
          INNER JOIN mfg_color mc
          ON pd.color_id = mc.color_id"
;
$result mysql_query($query);
$rows mysql_num_rows($result);

$qtycheck 0;
for (
$i 0$i $rows; ++$i) {
    
extract(mysql_fetch_array($result));
    
    
$postqty $_POST["qty$i"];
    if (
$postqty $qty) { 
        
$red 'red';
        
$qtycheck += 1;
        
$stockerror "<br /><span class='stockerror'>*Only <span class='qty'>$qty</span> In Stock</span>";
    }
    elseif (
$postqty 0) {
        
$red '';
        
$stockerror '';
        
$sid session_id();
        
$query2 "SELECT c.item_no
                   FROM cart c
                   WHERE c.item_no = 
$item_no AND c.session_id = $sid";
        
$result2 mysql_query($query2);
        
        if (
mysql_num_rows($result2) == 0) {
            
$query3 "INSERT INTO `lashelles`.`cart` (`cart_id`, `item_no`, `cart_qty`, `session_id`, `date`) 
                       VALUES (NULL, '
$item_no', '$postqty', '$sid', NOW());";
            
mysql_query($query3);
            
        }
        else {
            
$query3 "UPDATE `lashelles`.`cart`
                       SET cart_qty = cart_qty + 
$postqty
                       WHERE item_no = 
$item_no AND session_id = $sid";
            
mysql_query($query3);
        }
        (
mysql_query($query3)) ? $postqty '' $postqty;
    }
    else {
        
$red '';
        
$stockerror '';
    }
        
    
    (
$postqty == '') ? $value $value $postqty;
    
    (
$i == 1) ? $alt "DDDDDD" $alt "FFFFFF";
    (
$font == 'W') ? $font "FFFFFF" $font "000000";
    echo <<<_END
<tr style="background:#$alt;">
    <td>
$color_no</td>
    <td style="background:#
$hex; color:#$font;">$color_name</td>
    <td>
$series</td>
    <td>
$size</td>
    <td class="retail">List: $
$retail</td>
    <td>$
$price</td>
    <td>
$qty</td>
    <td style="text-align:right;"><input type="text" size="3" value="
$value" name="qty$i" style="border:1px solid $red;"/>$stockerror</td>
    
</tr>
_END;
}

?>
<tr><td colspan="8" style="border:0; text-align:right;"><input class="addtocart" type="submit" value="ADD TO CART" name="addtocart" /></td></tr>
</table>

</form>


andformore 01-12-2010 03:40 AM

Are you still having issues with this?

andformore 01-12-2010 05:54 AM

What I would Do
 
This is how I would do it. ITs well commented to help you along. Let me know if yo have any questions. I hope it works :-)

PHP Code:

<?php

/*
 * General Notes:
 *
 * I personally avoid using the extract() function for dealing with queries. It makes
 * variables pop out of no where and the code becomes harder to read, both for third
 * parties and yourself at a later date. I prefer doing $mysql_returned_array["database_field"]
 *
 */

session_start();

require_once 
'lib/database.php';

function 
get_shopping_cart(){
  
$shopping_cart = array();
  
$sid session_id();
  
$query2 "SELECT c.item_no
             FROM cart c
             WHERE c.session_id = 
$sid";
  
$result2 mysql_query($query2);
  if(
mysql_num_rows($result2) > 0){
    while(
$cart_row mysql_fetch_array($result2)){
      
$shopping_cart[$cart_row['item_no']] = true;
    }
  }

  return 
$shopping_cart;
}

$main_error_message "";
$updated_items      0;
$inserted_items     0;

///get all colors from the database, set to array
$all_colors = array();
$query "SELECT mc.color_no, mc.color_name, mc.hex, mc.font, mc.series, pd.size, pd.retail, pd.price, pd.qty, pd.item_no
          FROM product pd
          INNER JOIN mfg_color mc
          ON pd.color_id = mc.color_id"
;
$result mysql_query($query);
if(
mysql_num_rows($result) > 0){
  while(
$color_array mysql_fetch_array($result)){
    
$all_colors[$color_array['color_id']] = $color_array;
  }
}


//was anything posted this page load?
if($_POST["post_flag"] == 1){

  
//set a boolean here to keep track of weather or not we have sufficient quantity in stock
  
$sufficient_quantity true;

  
//something was posted, so lets loop through each color once to make sure we have enough in stock of everything they requested
  
foreach($all_colors as $one_color){

    
//instead of extract, we will manually set variables here
    
$color_id $one_color["color_id"];
    
$quantity $one_color["qty"];

    
//note the use of the color_id to identify the quantity field instead of $i. Using $i makes it hard because it is an arbitrary number and forces you to do more work and write more confusing code.
    
$postqty $_POST["qty".$color_id];

    
//did they order more than we have of this color?
    
if($postqty $quantity){
      
//uh-oh, they asked for more than we have of this color. lets handle the error.
      
$all_colors[$color_id]["error_message"] = "*Only $quantity In Stock.";
      
//set our flag so we know not to process this order
      
$sufficient_quantity false;
    }

  }

  
//now, lets see if we have enough quantity to update the shopping cart
  
if($sufficient_quantity){
    
//we have enough. lets process the order

    //first, lets get the contents of their cart
    
$shopping_cart get_shopping_cart();

    
//now, we'll loop through all colors again, this time either inserting into the cart or updating its quantities
    
foreach($all_colors as $one_color){

      
//instead of extract, we will manually set variables here
      
$color_id $one_color["color_id"];
      
$quantity $one_color["qty"];
      
$item_no  $one_color["item_no"];
      
$sid session_id();

      
//note the use of the color_id to identify the quantity field instead of $i. Using $i makes it hard because it is an arbitrary number and forces you to do more work and write more confusing code.
      
$postqty $_POST["qty".$color_id];

      
//did they order this color?
      
if($postqty 0){
        
//they did order it. is it in their cart already?
        
if($shopping_cart[$item_no] == true){
          
//its in the cart, lets update qunatity
          
$update_cart "UPDATE `lashelles`.`cart`
                       SET cart_qty = cart_qty + 
$postqty
                       WHERE item_no = 
$item_no AND session_id = $sid";
          if(
mysql_query($update_cart)){
            
$updated_items++;
          }
        }
        else{
          
//its not in the cart, lets insert it.
          
$update_cart "INSERT INTO `lashelles`.`cart` (`cart_id`, `item_no`, `cart_qty`, `session_id`, `date`)
                       VALUES (NULL, '
$item_no', '$postqty', '$sid', NOW());";
          if(
mysql_query($update_cart)){
            
$inserted_items++;
          }
        }
      }

    }

  }
  else{
    
//not enough quantity. we will not update cart.
    
$main_error_message "Error: We lacked the quantities required to update your cart";
  }

}

echo 
$main_error_message;
echo 
"Updated $updated_items Items and Inserted $inserted_items Succesfully!";


?>
<!-- just so you know, you're missing some HTML here :-) -->
<head>
<link rel="stylesheet" type="text/css" media="screen" href="include/screen.css">
</head>

<form action="<?php echo $_SERVER['PHP_SELF'?>" method="post">
  <!--
  Its nice to add a post flag sometimes, that way we only enter the php code
  to handle the post if the user actually posted something
  -->
<input type="hidden" name="post_flag" value="1">
<table id="colorchart" cellpadding="0" cellspacing="0">
<tr style="background:#CCCCCC;">
    <th>No.</th>
    <th>Color</th>
    <th>Series</th>
    <th>Size</th>
    <th>&nbsp</th>
    <th>Price</th>
    <th>Avail.</th>
    <th style="text-align:right; padding-right:25px;">Qty.</th>
</tr>

<!-- finaly, we will loop once more and display everything -->
<?php 
  $c 
0;

  foreach(
$all_colors as $one_color): 
  
  
$c++;
  
//i normally wouldnt use extract here either, im just lazy right now
  
extract($one_color);
?>
  <tr <?=($c ==0) ? "class=\"light\" " "class=\"dark\" " ?>>
    <td><?=$color_no ?></td>
    <td style="background:#<?=$hex ?>; color:#<?=($font == 'W') ? $font "FFFFFF" $font "000000"?>;"><?=$color_name ?></td>
    <td><?=$series ?></td>
    <td><?=$size ?></td>
    <td class="retail">List: $<?=$retail ?></td>
    <td>$<?=$price ?></td>
    <td><?=$qty ?></td>
    <td style="text-align:right;"><input type="text" size="3" value="$value" name="qty$color_id" style="border:1px solid;"/>$error_message</td>
  </tr>
<?php endforeach; ?>
  <tr>
    <td colspan="8" style="border:0; text-align:right;">
      <input class="addtocart" type="submit" value="ADD TO CART" name="addtocart" />
    </td>
  </tr>
</table>

</form>
All Done!
<?php
/*
 * Begin old code
 
$qtycheck = 0;
for ($i = 0; $i < $rows; ++$i) {
    extract(mysql_fetch_array($result));

    $postqty = $_POST["qty$i"];
    if ($postqty > $qty) {
        $red = 'red';
        $qtycheck += 1;
        $stockerror = "<br /><span class='stockerror'>*Only <span class='qty'>$qty</span> In Stock</span>";
    }
    elseif ($postqty > 0) {
        $red = '';
        $stockerror = '';
        $sid = session_id();
        $query2 = "SELECT c.item_no
                   FROM cart c
                   WHERE c.item_no = $item_no AND c.session_id = $sid";
        $result2 = mysql_query($query2);

        if (mysql_num_rows($result2) == 0) {
            $update_cart = "INSERT INTO `lashelles`.`cart` (`cart_id`, `item_no`, `cart_qty`, `session_id`, `date`)
                       VALUES (NULL, '$item_no', '$postqty', '$sid', NOW());";
            mysql_query($update_cart);

        }
        else {
            $update_cart = "UPDATE `lashelles`.`cart`
                       SET cart_qty = cart_qty + $postqty
                       WHERE item_no = $item_no AND session_id = $sid";
            mysql_query($update_cart);
        }
        (mysql_query($update_cart)) ? $postqty = '' : $postqty;
    }
    else {
        $red = '';
        $stockerror = '';
    }


    ($postqty == '') ? $value = 0 : $value = $postqty;

    ($i % 2 == 1) ? $alt = "DDDDDD" : $alt = "FFFFFF";
    ($font == 'W') ? $font = "FFFFFF" : $font = "000000";
    echo <<<_END
<tr style="background:#$alt;">
    <td>$color_no</td>
    <td style="background:#$hex; color:#$font;">$color_name</td>
    <td>$series</td>
    <td>$size</td>
    <td class="retail">List: $$retail</td>
    <td>$$price</td>
    <td>$qty</td>
    <td style="text-align:right;"><input type="text" size="3" value="$value" name="qty$color_id" style="border:1px solid $red;"/>$stockerror</td>

</tr>
_END;
}

 * end old code
 */
?>



All times are GMT. The time now is 09:08 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0