Jump to content

Shopping cart app help


James0231

Recommended Posts

I've been trying to make a shopping cart application in php but my code is still broken. I've tried to fix it  but I still can't, therefore I'm asking for help now. I'll attach the file and if someone is willing to take a look at my index then i'd appreciate it. Note: I'm still not all that great at programming

shopping cart.zip

Edited by James0231
Link to comment
Share on other sites

since you didn't ask any specific question, which is what we need in order to specifically help you with any problem you are having, here's a general list of things about your current code -

 

1) post method form processing code should be separate from any get method code. these are two separate concerns and should be completely separated in your code. post method form processing code should check if a form was submitted at all, validate any inputs, and create/update/delete the data. after you successfully (no errors) process any post method form data, you should do a header() redirect back to the exact same url of the page. this will cause a get request for your page. you can then display the result of what the form processing code altered.

 

2) your cart should only contain the key (item id) and the quantity. all the other information is derived data and should not be stored in the cart.

 

3) don't use the global keyword to bring data into a function. pass any input data into a function as a call-time parameter.

 

4) you should only have ONE instance of your main html document. everything that is common from the <!DOCTYPE tag through to the </html> tag should be a single 'template'. only the content section that's different should be in your view. you should store the output from processing the view code in a php variable, then just echo that php variable in the one main html/document template at the correct location. i would either put or include the main html document at the end of your index.php file.

 

5) in cart_view.php, to display the contents of the cart, loop over the cart data (which will be just the item keys and quantities), use the key to get the name and cost from the $products array, calculate the item total from the quantity and the cost, and sum up each item cost to get the order total.

 

simplifying the cart to only hold the key/quantity will make a lot of your php code go away.

 

also, i just noticed that you don't have any session_start() in the code, so none of your $_SESSION variables will work. you need to have php's error_reporting set to E_ALL and display_errors set to ON (preferably in your php.ini) to get php to help you by reporting and displaying all the errors it detects. if you layout the code in your main file like suggested at the following link, it will help organize and make your code foolproof (a session_start() would be part of the initialization section) - http://forums.phpfreaks.com/topic/297824-database-issues-and-working/?do=findComment&comment=1519095

Edited by mac_gyver
Link to comment
Share on other sites

What does "broken" mean?

Broken as in 'It's not doing what it supposed to do' which as the other person mentioned a bunch of stuff that was missing in my code.  :o

 

since you didn't ask any specific question, which is what we need in order to specifically help you with any problem you are having, here's a general list of things about your current code -

 

1) post method form processing code should be separate from any get method code. these are two separate concerns and should be completely separated in your code. post method form processing code should check if a form was submitted at all, validate any inputs, and create/update/delete the data. after you successfully (no errors) process any post method form data, you should do a header() redirect back to the exact same url of the page. this will cause a get request for your page. you can then display the result of what the form processing code altered.

 

2) your cart should only contain the key (item id) and the quantity. all the other information is derived data and should not be stored in the cart.

 

3) don't use the global keyword to bring data into a function. pass any input data into a function as a call-time parameter.

 

4) you should only have ONE instance of your main html document. everything that is common from the <!DOCTYPE tag through to the </html> tag should be a single 'template'. only the content section that's different should be in your view. you should store the output from processing the view code in a php variable, then just echo that php variable in the one main html/document template at the correct location. i would either put or include the main html document at the end of your index.php file.

 

5) in cart_view.php, to display the contents of the cart, loop over the cart data (which will be just the item keys and quantities), use the key to get the name and cost from the $products array, calculate the item total from the quantity and the cost, and sum up each item cost to get the order total.

 

simplifying the cart to only hold the key/quantity will make a lot of your php code go away.

 

also, i just noticed that you don't have any session_start() in the code, so none of your $_SESSION variables will work. you need to have php's error_reporting set to E_ALL and display_errors set to ON (preferably in your php.ini) to get php to help you by reporting and displaying all the errors it detects. if you layout the code in your main file like suggested at the following link, it will help organize and make your code foolproof (a session_start() would be part of the initialization section) - http://forums.phpfreaks.com/topic/297824-database-issues-and-working/?do=findComment&comment=1519095

Thank you for all the pointers. I'll keep going over them as I attempt to make things work.

Link to comment
Share on other sites

Broken as in 'It's not doing what it supposed to do'

 

 

actually, that's not specific enough for us to help you. we already know your code isn't working/broken/doesn't do what it is supposed to do because you are posting a topic on a programming help forum. if it was working/not broken/does do what it is supposed to do, you wouldn't be posting here.

 

to get help, you must post actual errors and the code that they correspond to, symptoms (the output you actually observed, even if the output was a blank page) and at what point in the process they occurred, or specific questions.

Link to comment
Share on other sites

actually, that's not specific enough for us to help you. we already know your code isn't working/broken/doesn't do what it is supposed to do because you are posting a topic on a programming help forum. if it was working/not broken/does do what it is supposed to do, you wouldn't be posting here.

 

to get help, you must post actual errors and the code that they correspond to, symptoms (the output you actually observed, even if the output was a blank page) and at what point in the process they occurred, or specific questions.

You're right. I guess that it's all part of the learning process. As I mentioned before, I'm rather new to all of this so there's always something I can learn from people like you guys that have been doing programming for a long time.

Link to comment
Share on other sites

to get you going, here is your index.php code, rearranged as suggested -

<?php
// 1) initialization - create/define things your code needs - session_start(), require files holding configuration data/function definitions, setup an autoloader for class definitions...
session_start();

$errors = array(); // holds error messages. if empty, no errors, if not empty, at least one error.

$products = array();
$products['MMS-1754'] = array('name' => 'Flute', 'cost' => '149.50');
$products['MMS-6289'] = array('name' => 'Trumpet', 'cost' => '199.50');
$products['MMS-3408'] = array('name' => 'Clarinet', 'cost' => '299.50');

require_once('cart.php');

// 2) start of database dependent code - create a database connection. if you are using exceptions to handle database errors, this would be where the try block starts.
// none in this example

// 3) determine user state and permissions - check if the current user is logged in and retrieve any permissions the user has. the rest of the code on the page would make use of the logged in state and permissions to determine what code can be ran and what content will be produced.
// if you were doing this for real, you would require that the user be logged in/authenticated at some point

// 4) post method form processing - the post method form processing code, which creates/modifies/deletes data on the server, should come near the start of your file so that you aren't tempted to output anything to the browser before any data has been updated by the processing code. if your page has multiple sections of form processing code, you would have them all groped together in this section of code.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $action = filter_input(INPUT_POST, 'action');
    switch($action) {
    case 'add':
        $product_key = filter_input(INPUT_POST, 'productkey');
        $item_qty = filter_input(INPUT_POST, 'itemqty');
        add_item($product_key, $item_qty);
        break;
    case 'update':
        $new_qty_list = filter_input(INPUT_POST, 'newqty', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        foreach($new_qty_list as $key => $qty) {
            if (true) {
                update_item($key, $qty);
            }
        }
        break;
    case 'empty_cart':
        
        break;
    }

    if(empty($errors)){ // after successfully (no errors) processing any post data, do a header() redirect to the exact same url that the form submitted to. this will cause a get request for your page. this will cause the browser to forget that a form was submitted and it won't try to resubmit the form data if you refresh the page or browse back to the same url. this also enforces separation of concerns. post method form processing, which modifies data on the server is a separate concern from displaying data due to a get request for your page. if you want to display a one-time 'success' message after the header() redirect, pass it in a session variable, then clear he session variable after the the message gets displayed.
        $host = $_SERVER['HTTP_HOST'];
        $uri = $_SERVER['REQUEST_URI'];
        header("Location: http://$host$uri");
        die;
    }
    // if there are errors while processing any post data, you would not redirect, stay on the page, let the rest of the code on the page display the errors, (re)display the form, and repopulate the form fields with the previously submitted values.
}

// 5) get method business logic - code that produces/gets data needed for the dynamic content on the page. this code contains any database specific code that knows how to retrieve data from your database tables. the result of this code should be php variables that the code later on the page uses as its input. this code should contain NO html/css/javascript markup.
// since this code is using an array to define the product information, not used in this example

$action = filter_input(INPUT_GET, 'action'); // condition the get method action input

switch($action) {
    case 'show_cart':
        // not used in this example
       break;
    case 'show_add_item':
    default:
        // not used in this example
        break;
}

// 6) end of database dependent code - if you are using exceptions to handle database errors, you would catch the errors at this point. you can also destroy any query result resources and the database connection at this point since you won't need them any longer.
//none in this example

//7) get method presentation logic -
// code that knows how to take the data (database data, errors, form data...) from ALL the above code and
// produce the dynamic output for the page. if the output doesn't require any 'heavy' processing/formatting,
// just use the data directly in the html page/template code. the result from this code should be php variables
// that the html page/template uses. this code should contain NO database specific statements. if your page
// has multiple sections of get method presentation logic, you would have them all groped together in this
// section of code.

switch($action) {
    case 'show_cart':
        ob_start(); // capture the result of the included file
        include 'cart_view.php';
        $main_content = ob_get_contents();
        ob_end_clean();
        break;
    case 'show_add_item':
    default:
        ob_start(); // capture the result of the included file  
        include 'add_item_view.php';
        $main_content = ob_get_contents();
        ob_end_clean();     
        break;
}

//  html page/template - this section starts with the <!DOCTYPE ... tag and ends with the </html> tag. it is the actual html document that the dynamic output is put into to make the complete page. only simple php conditional logic/loops, function calls (that are responsible for producing output), and echo statements should be present in this section of code.
?>
<!DOCTYPE html>
<html>
<head>
    <title>My Guitar Shop</title>
    <link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
    <header>
        <h1>My Guitar Shop</h1>
    </header>
    <main>
    <?php
    if(!empty($errors)){
        echo 'The following error(s) occurred:<br>';
        foreach($errors as $error){
            echo "$error<br>";
        }
    }
    ?>
    <?php echo isset($main_content) ? $main_content : ''; ?>
    </main>
</body>
</html>

note: i didn't actually 'fix' anything in your code. in fact, for the places with php syntax errors due to incomplete logic, i just added a true keyword so that the code didn't throw any php syntax errors. faking/fixing up the php syntax and removing the common start/end of the html document from the two view files, lets your code run, but not necessarily do what you want, within the suggested page layout.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.