【问题标题】:PHP: shopping cart empty after clicking the add buttonPHP:单击添加按钮后购物车为空
【发布时间】:2018-06-16 16:54:51
【问题描述】:

根据标题,我在将产品添加到购物车时遇到了问题:它会显示一条窗口消息,说明产品已添加,但实际上它不存在。它给出了以下错误:

致命错误:不能使用 stdClass 类型的对象作为数组

the line is: <td><?php echo $value['item_name']; ?></td>

这里是代码文件reserve.php:

 <?php

  session_start();
  ini_set('display_errors', 1);
  $connect = mysqli_connect('127.0.0.1', 'root', '***********', 'Community Garden List');


  if (isset($_POST['add'])) {
    if (isset($_SESSION['cart'])) {
        $item_array_id = array_column($_SESSION['cart'], 'product_id');
        if (!in_array($_GET['id'], $item_array_id)) {
            $count = count($_SESSION['cart']);
            $item_array = array(
                'product_id' => $_GET['id'],
                'item_name' => $_POST['hidden_name'],
                'product_price' => $_POST['hidden_price'],
                'item_quantity' => $_POST['quantity'],
            );
            $_SESSION['cart'][$count] = $item_array;
            echo '<script>window.location="reserve.php"</script>';
        } else {
            echo '<script>alert("Product is already Added to Cart")</script>';
            echo '<script>window.location="reserve.php"</script>';
        }
    } else {
        $item_array = array(
            'product_id' => $_GET['id'],
            'item_name' => $_POST['hidden_name'],
            'product_price' => $_POST['hidden_price'],
            'item_quantity' => $_POST['quantity'],
        );
        $_SESSION['cart'][0] = $item_array;
    }
 }

 if (isset($_GET['action'])) {
    if ($_GET['action'] == 'delete') {
        foreach ($_SESSION['cart'] as $keys => $value) {
            if ($value['product_id'] == $_GET['id']) {
                unset($_SESSION['cart'][$keys]);
                echo '<script>alert("Product has been Removed...!")</script>';
                echo '<script>window.location="reserve.php"</script>';
            }
        }
    }
 }
 ?>

    ?>

html代码

 <?php

     $query = 'SELECT * FROM product ORDER BY serial ASC';
     $result = mysqli_query($connect, $query);

     if (mysqli_num_rows($result) > 0) {
         while ($row = mysqli_fetch_array($result)) {
             ?>
             <div class="col-md-4">
            <form method="post" action="reserve.php?action=add&id='.$row['id'].">
            <div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">

                <img src="<?php echo $row['image']; ?>" class="img-responsive" style="width:100%;>
            <h5 class="text-info"><?php echo $row['pname']; ?></h5>
            <h5 class="text-danger">€ <?php echo $row['price']; ?></h5>
            <h5 class="text-info"><?php echo $row['pdescription']; ?></h5>
            <input type="text" name="quantity" class="form-control" value="1">
            <input type="hidden" name="hidden_name" value="<?php echo $row['pname']; ?>">
            <input type="hidden" name="hidden_price" value="<?php echo $row['price']; ?>">
            <input type="hidden" name="hidden_pdescription" value="<?php echo $row['pdescription']; ?>">
            <input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
            </div>
            </form>
            </div>
                }
        }
        ?>

 <?php
                if(!empty($_SESSION["cart"])){
                    $total = 0;
                    foreach ($_SESSION["cart"] as $key => $value) {
                        ?>
                        <tr>
                            <td><?php echo $value["item_name"]; ?></td>
                            <td><?php echo $value["item_quantity"]; ?></td>
                            <td>$ <?php echo $value["product_price"]; ?></td>
                            <td>
                                $ <?php echo number_format($value["item_quantity"] * $value["product_price"], 2); ?></td>
                            <td><a href="Cart.php?action=delete&id=<?php echo $value["product_id"]; ?>"><span
                                        class="text-danger">Remove Item</span></a></td>

                        </tr>
                        <?php
                        $total = $total + ($value["item_quantity"] * $value["product_price"]);
                    }
                        ?>
                        <tr>
                            <td colspan="3" align="right">Total</td>
                            <th align="right">$ <?php echo number_format($total, 2); ?></th>
                            <td></td>
                        </tr>
                        <?php
                    }
                ?>
            </table>
        </div>

    </div>

我在这行之后尝试了print "&lt;pre&gt;"; var_dump($row); exit;:foreach e($_SESSION['cart'] as $key =&gt; $value) {,它带有一个里面有NULL 的表格。这是什么意思?

在此之前,我尝试将 $value['item_name'] 更改为 $value-&gt;item_name ,但出现以下错误:

注意:未定义的属性:stdClass::$item_name in

请您帮我了解一下问题所在吗?谢谢。

【问题讨论】:

    标签: php mysql add cart


    【解决方案1】:

    我解决了一些错误尝试将零件组装在正确的位置 我把所有修改的内容都放在这里,你应该复制你需要的粘贴部分。

    <?php
    
      session_start();
      ini_set('display_errors', 1);
      $connect = mysqli_connect('127.0.0.1', 'root', '******************', 'Community Garden List');
    
    
      if (isset($_POST['add'])) {
        if (isset($_SESSION['cart'])) {
            $item_array_id = array_column($_SESSION['cart'], 'product_id');
            if (!in_array($_GET['id'], $item_array_id)) {
                $count = count($_SESSION['cart']);
                $item_array = array(
                    'product_id' => $_GET['id'],
                    'item_name' => $_POST['hidden_name'],
                    'product_price' => $_POST['hidden_price'],
                    'item_quantity' => $_POST['quantity']//!!!,
                );
                $_SESSION['cart'][$count] = $item_array;
                //echo '<script>window.location="reserve.php"</script>';//   do not send content when you use sessions $_SESSION['cart'][0] = $item_array;
            } else {
               // echo '<script>alert("Product is already Added to Cart")</script>';
                //echo '<script>window.location="reserve.php"</script>';
            }
        } else {
            $item_array = array(
                'product_id' => $_GET['id'],
                'item_name' => $_POST['hidden_name'],
                'product_price' => $_POST['hidden_price'],
                'item_quantity' => $_POST['quantity']//!!!!!!!!!!!!  ?  ->,
            );
            $_SESSION['cart'][0] = $item_array;
        }
     }
    
     if (isset($_GET['action'])) {
        if ($_GET['action'] == 'delete') {
            foreach ($_SESSION['cart'] as $keys => $value) {
                if ($value['product_id'] == $_GET['id']) {
                    unset($_SESSION['cart'][$keys]);
                    echo '<script>alert("Product has been Removed...!")</script>';
                    echo '<script>window.location="reserve.php"</script>';
                }
            }
        }
     }
    
    
         $query = 'SELECT * FROM product ORDER BY serial ASC';
         $result = mysqli_query($connect, $query);
    
         if (mysqli_num_rows($result) > 0) {
             while ($row = mysqli_fetch_array($result)) {
                 die();
    $tmimi1=<<<mimi1
    <div class="col-md-4">
    <form method="post" action="reserve.php?action=add&id={$row['id']}">
    <div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
    
    <img src="{$rr1}" class="img-responsive" style="width:100%;">
    <h5 class="text-info">{$row['pname']}</h5>
    <h5 class="text-danger">€{$row['price']}</h5>
    <h5 class="text-info">{$row['pdescription']}</h5>
    <input type="text" name="quantity" class="form-control" value="1">
    <input type="hidden" name="hidden_name" value="{$row['pname']}">
    <input type="hidden" name="hidden_price" value="{$row['price']}">
    <input type="hidden" name="hidden_pdescription" value="{$row['pdescription']}">
    <input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
    </div>
    </form>
    </div>
    mimi1;
             }
    }
    echo($tmimi1);
                    if(!empty($_SESSION["cart"])){
                        $total = 0;
                        foreach ($_SESSION["cart"] as $key => $value) {
    $tmimi2 =<<<mimi2
                            <tr>
                                <td>{$value["item_name"]}</td>
                                <td>{$value["item_quantity"]}</td>
                                <td>${$value["product_price"]}</td>
                                <td>$
    mimi2;
    echo($tmimi2);
    echo number_format($value["item_quantity"] * $value["product_price"], 2);
    
    $tmimi2=<<<mimi3
    </td>
                                <td><a href="Cart.php?action=delete&id={$value["product_id"]}"><span
                                            class="text-danger">Remove Item</span></a></td>
    
                            </tr>
    mimi3;
    echo($tmimi3);
                            $total = $total + ($value["item_quantity"] * $value["product_price"]);
                        }
    $tmimi2=<<<mimi4
                            <tr>
                                <td colspan="3" align="right">Total</td>
                                <th align="right">$ 
    mimi4;
    echo($tmimi4);
    echo number_format($total, 2); 
    $tmimi2=<<<mimi5
    </th>
                                <td></td>
                            </tr>
    mimi5;
    echo($tmimi5);                    }
    $tmimi2=<<<mimi6
                </table>
            </div>
    
        </div>
    mimi6;
    echo($tmimi6);
    ?>
    

    【讨论】:

    • 感谢 Costantin。我收到此错误:解析错误:语法错误,意外 '"',在 /opt/lampp/htdocs/ 中需要标识符 (T_STRING) 或变量 (T_VARIABLE) 或数字 (T_NUM_STRING)这行第 264 行的 cart/reserve.php: if(!empty($_SESSION["cart"])){ $total = 0;
    • 用''更改购物车中的“”,我得到另一个错误:解析错误:语法错误,意外''(T_ENCAPSED_AND_WHITESPACE),期望标识符(T_STRING)或变量(T_VARIABLE)或数字(T_NUM_STRING )....有什么问题?
    • 错误地编写代码(以您所做的方式会抓住很多错误)尝试从会话中获取第一个输入并且不在那里回显任何内容,然后保存您在会话中保存的内容,然后计算html 在每个页面上都有 {$var1} 在 $line = 所以使用这样的结构,这样你就可以轻松地编辑你的脚本了!如果您存储公共函数 = 任何 php 页面,您还应该包含一个文件!
    • 感谢 Costantin,我用谷歌搜索错误,试图修复它。但是我是初学者,很多编码我都不是很懂,只是现在学习。你知道我在哪里可以获得关于购物车的好教程吗?我不需要任何巨大的东西,它不是一个真正的商店,它只是一个学校项目。谢谢。
    【解决方案2】:

    您在发布答案之前删除了有关从在线天气数据中获取数组的帖子?我不知道如何向您发送您的要求,然后您在按下“发布答案”按钮之前删除问题!(如果您是 mimi 提出的,或者还有另一个 mimi=不确定)以防您在此之前询问我给你答案:

    <?php
    function print_r2($var){
    	echo('<h3>'.$var.':</h3><br>');
    	print_r($GLOBALS[$var]);echo('br');
    }
    function hr(){
    	echo('<hr>');
    }
    
    $lines=implode(file('http://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22'));
    print_r2('lines');hr();
    
    $data = json_decode($lines);
    print_r2('data');hr();
    print('wind obj:');print_r($data->wind);hr();
    print('speed:');print_r($data->wind->speed);hr();
    print('deg:');print_r($data->wind->deg);hr();
    ?>

    在我的屏幕上我得到了..push RUN CODE SNIPPET!

    <h3>lines:</h3><br>{"coord":{"lon":139.01,"lat":35.02},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":{"all":0},"dt":1485792967,"sys":{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}br<hr><h3>data:</h3><br>stdClass Object
    (
        [coord] => stdClass Object
            (
                [lon] => 139.01
                [lat] => 35.02
            )
    
        [weather] => Array
            (
                [0] => stdClass Object
                    (
                        [id] => 800
                        [main] => Clear
                        [description] => clear sky
                        [icon] => 01n
                    )
    
            )
    
        [base] => stations
        [main] => stdClass Object
            (
                [temp] => 285.514
                [pressure] => 1013.75
                [humidity] => 100
                [temp_min] => 285.514
                [temp_max] => 285.514
                [sea_level] => 1023.22
                [grnd_level] => 1013.75
            )
    
        [wind] => stdClass Object
            (
                [speed] => 5.52
                [deg] => 311
            )
    
        [clouds] => stdClass Object
            (
                [all] => 0
            )
    
        [dt] => 1485792967
        [sys] => stdClass Object
            (
                [message] => 0.0025
                [country] => JP
                [sunrise] => 1485726240
                [sunset] => 1485763863
            )
    
        [id] => 1907296
        [name] => Tawarano
        [cod] => 200
    )
    br<hr>wind obj:stdClass Object
    (
        [speed] => 5.52
        [deg] => 311
    )
    <hr>speed:5.52<hr>deg:311<hr>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多