How to display items using sessions

Furrukh Jamal

I am doing a opencourse project where I have to load a menu through a xml file and keep track of what the user buys and display it in a cart. Almost everything is done but I dont seem to access the items bought through the $_SESSIONS. The idea of how the web is running is simple it loads a particular category from the menu using a get variable and when an item is bought I am saving it in the $_SESSION as an array but when I visit cart.php I dont seem to see the record in $_SESSION

here is my index.php

<?php
session_start();

//loading the xml file
$dom = simplexml_load_file("../menu.xml");

// variable to store category id
$categoryid;

//to store all the data of a particular category id
$names = [];

//to store the name of the category
$categoryname;

//to count how many categories were in there in the xml file
$categorycount = count($dom->xpath("/menu/category"));

//Checking if the user visited via GET and if GET variable is set
if($_SERVER["REQUEST_METHOD"] == "GET")
{

    if(!isset($_GET["cat"]))
    {
        $categoryid = 1;
    }
    // checking if the variable is set within the limits of number of categories loaded
    else if (isset($_GET["cat"]) && ($_GET["cat"] > 0 && $_GET["cat"] <= $categorycount))
    {
        $categoryid = $_GET["cat"];
    }
    else
    {
        print("invalid category id");
    }

    //now loading the appropriate category from xml
    foreach($dom->xpath("/menu/category[@id = '{$categoryid}']") as $category)
    {
        $categoryname = $category->option;

        //saving the data
        foreach($category->name as $name)
        {
            $names[] = [
                    "optionname" => $name->type,
                    "small" => $name->small,
                    "large" => $name->large,
                    "general" => $name->general
                    ];
        }   
    }

    //loading the displaying files
    include("../views/header.php");
    include("../views/viewpage.php");

}

?>

the file header.php just got the head tag of the file so not pasting it here, table is produced by viewpage.php so its code is as follows

<body>
<div class = "cart">
    <a href= "cart.php">View Cart</a>
</div>
<?php if(isset($error)): ?>
<div class = "warning">
    <p>No Item was selected</p>
</div>
<?php endif; ?>
    <table>
        <thead>
            <tr>
                <th colspan = "4"><?= $categoryname ?></th>
            </tr>
            <tr>
                <th>Options</th>
                <th>Small</th>
                <th>Large</th>
                <th>General Price</th>
            </tr>
        </thead>
        <tbody>
            <form action = "buy.php" method = "POST">
                <?php foreach($names as $item): ?>
                <tr class = "even">
                    <td><?= $item["optionname"] ?></td>
                    <td>
                        <!-- checking every key value pair of $item if its empty and dynamically giving the names to inputs combining name and price-->
                        <?php if($item["small"] != ""): ?>
                        <?= $item["small"] ?>
                        <input type = "text" name = "<?= $item["optionname"]?>#<?=$item["small"]?>">
                        </input>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if($item["large"] != ""): ?>
                        <?= $item["large"] ?>
                        <input type = "text" name = "<?= $item["optionname"]?>#<?= $item["large"] ?>">
                        </input>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if($item["general"] != ""): ?>
                        <?= $item["general"] ?> 
                        <input type = "text" name = "<?= $item["optionname"]?>#<?= $item["general"] ?>">
                        </input>    
                        <?php endif; ?> 
                    </td>
                </tr>
                <?php endforeach ?>

        </tbody>
    </table>

        <input type = "submit" value = "Buy!">
    </form>

    <!-- printing the list to display categories using the categorycount variable-->
    <div class= "list">
        <h4>category</h4>
        <?php
            for($i = 1; $i <= $categorycount; $i++)
            {
                print("<ul>
                        <li><a href = \"?cat={$i}\">{$i}</a></li>
                      </ul>");
            }   
        ?>
    </div>  
</body>

the buying process is done by buy.php, its code is as follows

<?php
session_start();
//print_r($_POST);
//print("</br>");

$quantity;
$typename;
$price;
foreach($_POST as $key => $value)
{
    //array to save category name, its size, price and quantity of each item
    $cart = [];

    if(!empty($value))
    {
        $quantity = $value;
        //print($key ." val ". $value);
        //print("</br>");
        //breaking the input name to get the type thats in xml from input name, the section before '#' 
        $typename = strstr($key, "#", true);

        //getting the part that comes after '#'
        $price = substr($key, strpos($key, "#") + 1);

        //now converting the '_' to a space and '.'
        $typename = str_replace("_", " ", $typename);
        $price = str_replace("_", ".", $price);

        //checking if '&' in name is present then convert if to &amp;
        /*if(strpos($typename, "&"))
        {
            $typename = str_replace("&", "&amp;", $typename);
        }*/ 

        //print($typename);
        //print("</br>");
        //print($price);
        //print("</br>");

        //opening the xml file to search
        $dom = simplexml_load_file("../menu.xml");

        //searching
        foreach($dom->xpath("/menu/category") as $category)
        {
            //iterating over every name tag in xml
            foreach($category->name as $name)
            {
                //print("</br>checking on run{$name->type} </br></br>");
                //checking every type tag
                if($name->type == $typename)
                {
                    //storing what category name the type belongs to
                    $cartcategoryname = $category->option;
                    //print("the category is {$cartcategoryname}</br>");

                    //test to see what size the above matched type is
                    if($name->small == $price)
                    {
                        $size = "small";
                    }
                    else if($name->large == $price)
                    {
                        $size = "large";
                    }
                    else
                    {
                        $size = "general";
                    }
                }

            }

            /*adding the name,size,type quantity in an array
             * which would be added to $_SESSION and the array
             * would be wiped clean.*/ 
            $cart = [
                "category" => $cartcategoryname,
                "type" => $typename,
                "size" => $size,
                "price" => $price,
                "quantity" => $quantity
                ];  
        }   

        $_SESSION["cart"][] = $cart;
    }

    /* name of category, its type, size, price and quantity in 
     * arry cart */
    /*$cart[] = [
            "category" => $cartcategoryname,
            "type" => $typename,
            "size" => $size,
            "price" => $price,
            "quantity" => $quantity
            ];*/


    //print_r($cart);
    //print("</br></br></br>");

    //pushing the above created arror into session global
    //$_SESSION["cart"][] = $cart;      
}
//print_r($_SESSION);
//print("</br>");

/*foreach($_SESSION["cart"] as $cartitem)
{
    print($cartitem["category"]."</br>");
    print($cartitem["quantity"]."</br>");
    print($cartitem["type"]."</br>");
}*/ 



$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'index.php?cat=1';
header("Location: http://$host$uri/$extra");
exit;

//header("Location: index.php?cat=1");
//exit;

?>

now when I use print_r($_SESSION) in cart.php I cant see any of the things code for it is

<?php
session_start();
foreach($_SESSION["cart"] as $cartitem)
{
    print($cartitem["category"]."</br>");
    print($cartitem["quantity"]."</br>");
    print($cartitem["type"]."</br>");
}
//phpinfo();

?>

the xml file is as follows

<menu>
<category id = '1'>
    <option>Pizzas</option> 
    <name>
        <type>Tomato &amp; Cheese</type>
        <small>5.50</small>
        <large>9.75</large>
        <general/>
    </name>
    <name>
        <type>Onions</type>
        <small>6.85</small>
        <large>10.85</large>
        <general/>
    </name>
</category>
<category id = '2'>
    <option>Side Orders</option> 
    <name>
        <type>Onion Rings</type>
        <small>2.60</small>
        <large>2.95</large>
        <general/>
    </name>
    <name>
        <type>French Fries</type>
        <small>2.85</small>
        <large>3.85</large>
        <general/>
    </name>
</category>
Furrukh Jamal

ok got the $_SESSION working in cart.php, by including error_reporting(E_ALL); ini_set("display_errors", 1) I got an error Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file] on line 0 did a bit of google search and found out that xml data is still a xml data and one needs to type cast it into a string. Doing that allowed me to see the session variables in cart.php

Collected from the Internet

Please contact javaer1[email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Use sessions for display notifications?

how to use sessions and arrays in a database query to store and display data

Add items to cart in php using sessions

How to select and display items in a dropdown using handlebars with bootstrap

How to acquire graph token without using sessions?

How do I display more JSON items in HTML using WebKit?

How to align items not working unless using display flex?

How do i display my items in a row ( using php and bootstrap to display all items from a database)

How to display items in RecyclerView running inside Fragment using MVVM?

How to display items inline using angular's *ngFor

How to display multiple items in a dictionary?

How to display multiple items using puts?

How to display a specific amount of items from an array using React

How can I display userID in Sessions?

Using CSS to display items as ordered list

how to Modify a form using php sessions

How to display unlimited items horizontally?

How to set default DISPLAY for all SSH sessions?

How to Increment the quantity using ajax, php sessions?

how to display arraylist items in toast?

How to count SESSIONS to display total number of logged in users on the site

Display array items with custom space using angularjs

How to display items of linked model

How can I save pandas display options for further sessions?

How to destroy PHP Sessions Using Javascript Ajax

How to display one item on top of other items by using Flexbox?

How can I display array items using a loop?

How to display single items from array using JS/JQuery

how to display nested items using fetchData method in react.js