WibblyWobbly
WibblyWobbly

Reputation: 145

Shopping cart not displaying products, intval?

I am creating a PHP shopping cart linked to SQL database, from a tutorial i am following.

The code below SHOULD display all my products, however I believe that the

$id = intval($_GET['id']);

section is messing it up. The SKU's of the products are Varchar, not integers, so I am lead to believe that this is causing the problem with "intval". Is there another datatype I can insert that will display my products again?

<?php

if (isset($_GET['action']) && $_GET['action'] == "add")
{
    $id = intval($_GET['id']);

    if(isset($_SESSION['cart'][$id]))
    {
        $_SESSION['cart'][$id]['quantity']++;
    } 
    else 
    {
        $sql2   = "SELECT * FROM products WHERE SKU={$id}";
        $query2 = mysql_query($sql2);

        if(mysql_num_rows($query2) != 0)
        {
            $row2 = mysql_fetch_array($query2);
            $_SESSION['cart'][$row2['SKU']] = array("quantity => 1, "price" => $row['price']);

        } 
        else 
        {
            $message = "This product id is invalid";
        }
    }
}
?>
<h2 class="message"><?php if(isset($message)){echo $message; ?></h2>
<h1>Product Page</h1>
<table>
    <tr>
        <th>Name</th>
        <th>Description</th>
        <th>Price</th>
        <th>Action</th>
    </tr>

    <?php
    $sql   = "SELECT * FROM products ORDER BY SKU ASC";
    $query = mysql_query($sql)or die(mysql_error());

    while($row = mysql_fetch_assoc($query))
    {
        ?>
        <tr>
            <td><?php echo $row['name']; ?></td>
            <td><?php echo $row['Description']; ?></td>
            <td><?php echo "£" . $row['price']; ?></td>
            <td><a href="index.php?page=products&action=add&id=<?php echo $row['SKU']; ?>">Add to Cart</a></td>
        </tr>

        <?php
    }
    ?>

</table>

Upvotes: 0

Views: 183

Answers (2)

msturdy
msturdy

Reputation: 10794

Check the docs for intval() and you'll see that this method returns 0 when the variable isn't an integer.

if you're looking to search for this, you can just change the line to:

$id = $_GET['id'];

to get the variable as a string

However there are two things to bear in mind with this:

Upvotes: 0

Martin
Martin

Reputation: 410

You are missing an ending quote here:

$_SESSION['cart'][$row2['SKU']] = array("quantity" => 1, "price" => $row['price']);

You're also missing a } sign

<h2 class="message"><?php if(isset($message)){echo $message; } ?> </h2>

Upvotes: 1

Related Questions