添加到会话数组

时间:2018-05-28 18:04:55

标签: php html

<?php
 session_start();
 include("#nav.php");
 include("dbconnectie.php");
 echo "Plaatsingen: ";
        $query = $db->prepare("SELECT * FROM shop");
        $query->execute();
        $result = $query->fetchALL(PDO::FETCH_ASSOC);
        echo "<table>";
            foreach($result as &$data) {
                echo "<tr>";
                $img = $data['img_url'];
                echo "<td>" . $data["brand"] . "</td>";
                echo "<td>" . $data["model"] . "</td>";
                echo "<td> Condition: " . $data["cond"] . "/100 </td>";
                echo "<td> Prijs: &dollar; " . number_format($data["price"],2,",",".") . "</td>";
                    echo "<td> <img src='$img' width='400' height='300' ></img> </td>";
                echo "<td> Plaatsing nummer: " . $data['id_img'] . "</td>";
                echo "</tr>";
                echo "<br>";
            }
        echo "</table>";
        if(isset($_POST['atc']))
        {
            if($_SESSION['on']){
                $myarray = array('0');
                $addtoarray = $_GET['id'];
                array_push($myarray, $addtoarray);
                $_SESSION['cart'] = $myarray;
                echo "Toegevoogd aan uw winkelmandje.";
                var_dump($_SESSION['cart']);
            }else 
            {
                echo "Log eerst in!";
            }

        }
?>

<html>
    <title>Just for kicks</title>
    <header>
    </header>
    <body>
        <form method='post' action=''>
            Plaatsing nummer invoeren:
             <input type='number' name ='id' value ='id'><br>
             <button type="submit" class="submit" name="atc" value="atc">Winkelmadje</button><br><br>
        </form>
    </body>
</html>

在第25行和第31行之间,我试图在会话数组中添加数字,但我不确定如何,因为这显然不起作用。它不会在表单部分添加您填写的数字。但它似乎没有做任何事情。

1 个答案:

答案 0 :(得分:1)

我将您的代码调整到最低限度,并添加了一些内联注释。我假设$_SESSION['cart']的内容是一个数组。

请注意:

  1. 始终使用POST
  2. 已删除输入值(value ='id'
  3. 检查$_SESSION['on']已删除
  4. 代码

    <?php
    // Start your session.
    session_start();
    
    // The form was submitted.
    if (isset($_POST['atc'])) {
    
        // Get the cart so we can append to it.
        // Assuming that the cart is an array.
        $cart = (array)$_SESSION['cart'];
    
        // Append the user's input to the end of the cart.
        $cart[] = $_POST['id'];
    
        // Store it in the session.
        $_SESSION['cart'] = $cart;
    
        // Dump out the session.
        var_dump($_SESSION);
    }
    ?>
    
    <html>
    <title>Just for kicks</title>
    <header>
    </header>
    <body>
    <form method='post'>
        <label> Plaatsing nummer invoeren:
            <input type='number' name='id'/>
        </label><br>
    
        <button type="submit" class="submit" name="atc" value="atc">Winkelmadje</button>
        <br><br>
    </form>
    </body>
    </html>