Page 1 of 2

action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 7:32 am
by geforcy
Hello,

I've been working on a simple shopping cart and want to put the cart functions all in one file. Currently I am debugging here and there, but there is still one issue. Though I know what the problem is, I don't know exactly how to solve it.

When I run the script I get the following error:
Notice: Undefined index: action in C:\wamp\www\shoppingcart\cart.php on line 6

I need to do something like:
$action = some kind of variable here.

But I don't know what to put in there. Been searching everywhere but there is no real good answer to it.
I don't get the error of course when I click on a add product on my productlist and refer the header to my cart.php. Because I then use the action and get a variable out of it.

Code: Select all

 <?php
include 'session.php';
include 'configdb.php';
include 'connectdb.php';
 
switch($_GET["action"])
{
case "add_item":
{
AddProduct($_GET["id"]);
ShowCart();
break;
}
case "update_item":
{
UpdateProduct($_GET["id"]);
ShowCart();
break;
}
case "remove_item":
{
RemoveItem($_GET["id"]);
ShowCart();
break;
}
default:
{
ShowCart();
}
}
 
function AddProduct($productId) {
$id_session = session_id();
$result = mysql_query("select count(*) from cart where sessionId = '" . $id_session . "' and productId = $productId");
 
$row = mysql_fetch_row($result);
$numRows = $row[0];
 
if($numRows == 0)
{
// This item doesn't exist in the users cart,
// we will add it with an insert query
 
@mysql_query("insert into cart(sessionId, productId, qty) values('" . $id_session . "', $productId, 1)");
header("Location: productlist.php");
}
else
{
// This item already exists in the users cart,
// we will update it instead
UpdateProduct($productId);
}
}
 
function UpdateProduct($productId, $qty) {
$id_session = session_id();
@mysql_query("update cart set qty = qty + 1 where sessionId = '" . $id_session . "' and productId = $productId");
header("Location: productlist.php");
}
 
function ShowCart(){
    $id_session = session_id();
    $totalCost = 0;
 
    $sql = "SELECT *
            FROM cart
            INNER JOIN products
            ON cart.productId = products.productId
            WHERE cart.sessionId = '" . $id_session . "'";
 
    // open the table and print a header row.
    if ($result=mysql_query($sql)) {
      while ($row=mysql_fetch_array($result)) {
        echo "".$row['productName']." ";
        echo "".$row['productDesc']." ";
        echo "".$row['productPrice']."<br>";
        $totalCost += $row["qty"] * $row["productPrice"];
      }
    }
    else {
      echo "<!-- SQL Error ".mysql_error()." -->";
    }
    echo "Total: ";
    echo number_format($totalCost, 2, ".", ",");
}
 
?>
 
Thank you already for your help,
Daan.

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 7:38 am
by jackpf
You need to check if $_GET['action'] exists before using it.

Try using isset().



Also...learn to indent 8O

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 7:44 am
by geforcy
Haha yes I know. I am bad at indent... But i'll improve that soon. I'll also post the answer for curious people WITH indent :wink:

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 7:54 am
by geforcy
After I knew to use isset I solved it with:

Code: Select all

 switch(isset($_GET['action']))

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 9:10 am
by jackpf
I don't see how that worked, since you'll be switch'ing the boolean value of isset().

Try this:

Code: Select all

switch((isset($_GET['action'])) ? $_GET['action'] : null)
Or...if you can handle the extra lines of code, you can put the whole thing in an if statement, so that the switch statement doesn't even execute...which would speed stuff up. Not that you'd notice.

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 11:07 am
by geforcy
Hey Jackpf, sorry I showed some extra stuff n my code. I only got switch(isset($_GET['action'])), at the moment. As far as I understand now the value return true even as it has no value in the action and works fine. And the if statement could be done as well, but why? those 0.000000001 of a seconds that it's faster? :wink:

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 11:23 am
by jackpf
No, seriously, it shouldn't work :P

If you go ?action=update_item, it should show add_item. No matter what you set, as long as it is set, it will return the first case, since they both evaluate to true.

Honestly, you've got the syntax wrong. :P

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 12:40 pm
by geforcy
Hmmm, it does work perfect, no errors whatsoever.

Code: Select all

<?php
include 'session.php';
include 'configdb.php';
include 'connectdb.php';
 
switch(isset($_GET['action'])) {
    case "add_item": 
        AddProduct($_GET["id"]);
        ShowCart();
        break;
    case "update_item": 
        UpdateProduct($_GET["id"]);
        ShowCart();
        break;
    case "remove_item": 
        RemoveItem($_GET["id"]);
        ShowCart();
        break;
    default:
        ShowCart();
}
 
function AddProduct($productId) {
    $id_session = session_id();
 
    $result = mysql_query("select count(*) from cart where sessionId = '" . $id_session . "' and productId = $productId");
    $row = mysql_fetch_row($result);
    $numRows = $row[0];
 
    if($numRows == 0) {
        // This item doesn't exist in the users cart,
        // we will add it with an insert query
        @mysql_query("insert into cart(sessionId, productId, qty) values('" . $id_session . "', $productId, 1)");
        header("Location: productlist.php");
    }
    else {
        // This item already exists in the users cart,
        // we will update it instead
        UpdateProduct($productId);
    }
}
 
function UpdateProduct($productId, $qty) {
    $id_session = session_id();
    @mysql_query("update cart set qty = qty + 1 where sessionId = '" . $id_session . "' and productId = $productId");
    header("Location: productlist.php");
}
 
function ShowCart(){
    $id_session = session_id();
    $totalCost = 0;
 
    $sql = "SELECT * 
            FROM cart
            INNER JOIN products 
            ON cart.productId = products.productId
            WHERE cart.sessionId = '" . $id_session . "'";
 
    // open the table and print a header row.
    if ($result=mysql_query($sql)) {
      while ($row=mysql_fetch_array($result)) {
        echo "".$row['productName']." ";
        echo "".$row['productDesc']." ";
        echo "".$row['productPrice']."<br>";
        $totalCost += $row["qty"] * $row["productPrice"];
      }
    } 
    else {
      echo mysql_error();
    }
    echo "Total: ";
    echo number_format($totalCost, 2, ".", ",");
}
 
?>
and this is the link to get the id and qty

Code: Select all

echo "<a href='cart.php?action=add_item&id=".$row["productId"]."'>Add Item</a><br>";
As I told you it works fine for now ;) :mrgreen: :crazy: :drunk: ... The action is true even when I just have <a href='cart.php'> which means no error? :)

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 12:46 pm
by John Cartwright
geforcy wrote:Hmmm, it does work perfect, no errors whatsoever.
Because it runs without errors doesn't mean there are no errors in your logic. Seriously, take the advice given. Your code is wrong.

A "true" value in your switch() will match any of those cases, since PHP is loosely typed. You need to compare against the value of the action.

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 12:50 pm
by jackpf
:yar:


:crazy: to you too



:P

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 3:47 pm
by geforcy
Sorry Jack, didnt meant like that. It is just weird that both solutions work and have the same result. Thanks for all your answers and have changed the code so it works "better" now :wink:

Code: Select all

f(isset($_GET['action'])) {
    switch($_GET['action']) {
        case "add_item": 
            AddProduct($_GET["id"]);
            break;
        case "update_item": 
            UpdateProduct($_GET["id"]);
            break;
        case "remove_item": 
            RemoveItem($_GET["id"]);
            break;
    }
}
else {
    ShowCart();
}

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 4:05 pm
by jackpf
Nice one ;)

I honestly don't think it worked.

Check this out:

Code: Select all

<?php
switch(isset($_GET['foo']))
{
    case 'this_will_always_return_true':
        echo 'this always returns true';
    break;
    case 'this_will_never_execute':
        echo 'never executes.';
    break;
}
?>
Then visit:
page.php?foo=this_will_never_execute

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 5:04 pm
by geforcy
(gives error when I copy/paste, but thats ok :wink: )
that will execute the second case and echo 'never executes.';

what I did: if action is true execute one of the cases. if not execute the else which is showcart(). which is when the link is just <a href="cart.php">Your Shopping Cart</a>, so there is no action involved. I only execute the action when <a href='cart.php?action=add_item&id=".$row["productId"]."'> is being clicked.

Thats the conclusion I have so far :). But I dont seem to get the point :cry: HELP :!: :mrgreen:

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 5:40 pm
by jackpf
:dubious: :dubious: :dubious:

Am I going mad?

That code doesn't give me an error. Nor does it ever execute the second statement.


Anyone else like to confirm this please? x]

Re: action in shopping cart needs index, but how?

Posted: Mon Sep 21, 2009 6:05 pm
by John Cartwright
I would suspect the error is claiming is because he forgot to use the ?action=whatever in the url, thus using the undefined variable.

And indeed, it will execute the first non false value (in our case the first case statement).