1

Im hoping someone can point me in the right direction of where im going wrong as I feel like im going around in circles!

Im putting together a simple shopping applications - its only very basic at the moment to demonstrate techniques.

The scenario is that there is one database table with items in. They have been split into a blue and red range of items.

On the index page the user has the option of going to either the blue or red items.

Once on the red (or blue) items page, items are displayed and current price and stock level is pulled from the database (MySQL). The user then selects one item and clicks the buy button to add it into their cart.

The page then redirects to the shopping cart page where the user can either update the quantity of the item, proceed to the checkout page or return to the 'red' or 'blue' ranges.

My issue is this.....

1) How do I set up my session array to capture the items as they are added on the buy 'click'?

So far I have this on the top of all pages...

<?php session_start();
?>

However only one item seems to be able to be added to the 'cart'.

This is how im pulling items from my DB:

<?php
$result = mysql_query ('SELECT * FROM items WHERE colour="red"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
  echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
  }
?></p>

2) This is the code for the form action under each item on either the red or blue page.

<form method="post" action="cart.php">
                    <p>
<input type="submit" name="submit" value="Buy" />
<input type="hidden" name="cart" value="add" />
<input type="hidden" name="item" value="redplate" />
                    </p>
                </form>

3) How do I display the 'ordered' item in the checkout page after any quantity updates on the shopping cart page?

So far this is what it on the shopping cart page - would I repeat this on the checkout page pulling with it the updated quantity??....

<?php
$submit = $_POST["submit"];

//Call the function and save all data into the array $_SESSION['form'] 
if($submit == "Buy"){setSessionVars();} 

function setSessionVars() {

    $item = array();
    foreach($_POST as $fieldname => $fieldvalue) {
        $item[$fieldname] = $fieldvalue;
    }  
    $_SESSION['cart'] = $item;

          echo "            <table> 
          <tr> 
            <td> 
                <img src=\"images/{$item['item']}.jpg\" />
                    <td/> 
            <td>
                {$item['item']} =
                    </td>
            <td> 
            <input type=\"text(5)\" name=\"value\" value=\"1\" />

            <input type=\"submit\" name=\"puchasedquan\" value=\"Click to update\" /> 

             </td> 
            </tr> 
                            </table>";
}
?>

Any help would be greatly appreciated!! I feel as if i'm traveling around in circles!

4 Answers 4

1

The problem with storing things in the PHP session vars is that they are stored in cookies, that means they require cookies to be turned on. Okay, most browsers have cookies set nowadays.

But how about if you read values directly from a client file, and put that into your database? Whats to stop someone from hacking the cookie file where it says "subtotal=10000" and changing the value to "subtotal=1", then push that through your system?

Your system would be more robust if you actually store the shopping session in your database, e.g.

CREATE TABLE tbl_shopping_session(
    id INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(id),
    php_session_key VARCHAR(32),
    coupon_id INT,
    FOREIGN KEY(coupon_id) REFERENCES tbl_coupons(id),
    updated TIMESTAMP /* a timestamp is added to find & del old sessions */
) ENGINE = InnoDB;

CREATE TABLE tbl_shopping_cart(
    shopping_session_id INT,
    FOREIGN KEY(shopping_session_id) REFERENCES tbl_shopping_session(id) ON DELETE CASCADE,
    product_id INT,
    FOREIGN KEY(product_id) REFERENCES tbl_products(id),
    cart_qty INT /* or DECIMAL(9,3) or something */,
    subtotal DECIMAL(18,4)
) ENGINE = InnoDB;

From there on you could get the picture... the php_session_key is used to identify the current shopping session, and the current session id is used to find & store the cart items in a separate table.

Sign up to request clarification or add additional context in comments.

Comments

1

The big mistake here is, you are putting all you datas on one session variable altogether, i.e. $_SESSION['cart'].

Since you want to insert multiple item on the sessions, you have use $_SESSION['cart'][] to insert the items.

Whenever you are trying to get the values stored, again use a for loop to read as well as .

foreach($_SESSION['cart'] as $cartItem) {
  $cartItem; // will have all the item individually on each pass
}

4 Comments

Thank you - just tried and it is still only showing one item once I go back and try to add more?
Make sure you have called session_start() on the top of every page.
I have called this on each page - I must have missed something further back!
@ez007, It seems like a server problem now. The session is resetting on every load.
0

try this

$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
    $item[$fieldname][] = $fieldvalue;
} 

5 Comments

Thanks!I just tried this but its pulling through 'Array" as the item name now and no image?
try print_r($whateveryouritemvariableis); what is the output?
ITs come up with an error? Im not even sure if ive defined one right...ill update my main Q with the coding for selecting the item from the database!
did you replace $whateveryouritemvariableis with $item? I meant do print_r($item); to see what the array looks like
This is what it prints: Array ( [submit] => Array ( [0] => Buy ) [cartaction] => Array ( [0] => add ) [item] => Array ( [0] => redplate ) ) -Thanks for your help!
0

The $_SESSION keys are being replaced when you add more, so really it's just overwriting an existing value, you could add this:

foreach($_POST as $fieldname => $fieldvalue) {
    // Now the array will be enumerated
    $item[$fieldname][] = $fieldvalue;
}  

print_r($item);

5 Comments

Thanks! Its throwing a parse error.....'Parse error: syntax error, unexpected $end.' The line it pointing to is blank so im not too sure...
Make sure your French Brackets {} are matching up, you might be missing them somewhere!
Array ( [submit] => Array ( [0] => Buy ) [cartaction] => Array ( [0] => add ) [item] => Array ( [0] => redplate ) ) Looks like its linking to the form submit on the actual item?
Try changing the $_POST to this: .. foreach($_POST['submit']
Done...now with another error! I tried: $item = array(); foreach($_POST['submit'] as $fieldname => $fieldvalue) { $item[$fieldname][ ] = $fieldvalue; } print_r($item); and the error was: Invalid argument supplied for foreach() in XXXXX on line 37 Array ( )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.