Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Frederick Alcantara
Frederick Alcantara
7,617 Points

Trying to move items from a shopping cart back to the inventory

I am trying to move items from my shopping cart to the inventory page. Here is the current code I have so far:

if(isset($_REQUEST['qty'])) { $qty = $_REQUEST['qty']; $sku = $_REQUEST['sku']; // Test that the requested number of items are in inventory: if ($qty){

            $sql = "UPDATE inventory SET in_stock = in_stock + $qty WHERE sku = '$sku'";
            $db ->query($sql);

            $sql ="INSERT INTO cart ( sku, in_cart ) VALUES( '$sku', $qty ) ON DUPLICATE KEY UPDATE in_cart = in_cart - $qty";
            $db -> query($sql);

            $sql = "DELETE FROM cart WHERE in_cart = 0";
            $db -> query($sql);
        }

}

$result = $db->query('Select * FROM cart LEFT JOIN inventory on inventory.sku = cart.sku' );

?>

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Shopping Cart</title> </head> <body> <div class="shop"> <div class="item"> <h3><?php echo "<a href='index.php'>Home </a>"; ?></h3>

    </div>
    <div class="cart">
        <p></p>

        <form action="" method="get">
        <?php 

            while ( $row = $result->fetch( PDO::FETCH_ASSOC ) ) {

            $cart = $row['in_cart'];
            $title = $row['title'];
            $price = $row['unit_price'];
            $sku2 = $row['sku'];

            echo "<h3>" . $title . "</h3>";

            echo "<select name='qty'>";
            for ($i=1; $i <= $cart; $i++) 
                { 
                     echo "<option>$i</option>" ;
                }
            echo "</select> <input type='submit' value='Remove from Cart' />";
            }   
        ?>   

            <input type="hidden" name="sku" value="<?php echo $_REQUEST['sku'] ?>"> 
            <p></p>
        </form> 
    </div>
</div>

</body> </html>