0

As per title, I have a problem when adding products to the cart: it would show a window message that says that the product has been added, but in truth it is not there. It gives the following error:

Fatal error: Cannot use object of type stdClass as array

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

Here is the code file 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 code

 <?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>

I've tried print "<pre>"; var_dump($row); exit; after this line: foreach e($_SESSION['cart'] as $key => $value) { and it comes a table with NULL inside. What does that mean?

Before that, i tried to change $value['item_name'] with $value->item_name , and i got the following error:

Notice: Undefined property: stdClass::$item_name in

Will you please help me to understand what's wrong? thank you.

Mimi
  • 3
  • 5

2 Answers2

0

i solve some errors try to assemble the parts in the right places i put all content modified here you should copy paste parts you need.

<?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);
?>
  • Thanks Costantin.I got this error:Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /opt/lampp/htdocs/cart/reserve.php on line 264 on this line: if(!empty($_SESSION["cart"])){ $total = 0; – Mimi Jan 07 '18 at 16:40
  • changing the "" in cart with '', I get another error: Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)....what is the problem? – Mimi Jan 07 '18 at 17:04
  • https://stackoverflow.com/questions/9583035/unexpected-t-encapsed-and-whitespace-expecting-t-string-or-t-variable-or-t-num –  Jan 07 '18 at 17:06
  • writing wrongly the code(in the way you did will grab you lots of errors) try to get first inputs from session and do not echo any content there,then save what you save in sessions, then compute html on every page with {$var1} inside $line =<< So use constructions like these so you will able to edit your scripts easy ! also you should include one file were you store commons functions =for any php page! –  Jan 07 '18 at 17:12
  • thanks Costantin, I google the error, trying to fix it. But I'm a beginner, I don't really understand a lot of coding, just learning now. Do you know where I can get a good tutorial on shopping cart? I don't need anything huge, it's not for a real shop, but it's just a school project. Thanks. – Mimi Jan 07 '18 at 17:25
  • i never use other scripts, but the best website where you can find something to complicate your life as beginner is github.com (https://www.google.it/search?dcr=0&q=github+php+ecommerce&spell=1&sa=X&ved=0ahUKEwj69dnJsMbYAhWL2KQKHTFSDA0QvwUIKSgA&biw=1536&bih=746) –  Jan 07 '18 at 17:43
  • i found one they said is simple https://github.com/marwenhlaoui/PhpbasicE-commerce –  Jan 07 '18 at 17:58
0

you deleted your post about grab an array from online weather data before to post you the answer? i don't know how to send you what you ask and then you delete the question before to push 'post the answer' button!(if was you mimi who ask or there is another mimi=not sure) in case you ask before that i post you the answer:

<?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();
?>

and on my screen i got ..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>