Now I know how to do it but I keep getting an error saying the index is undefined. A little about what I'm trying to do: I have a cart and I want to update the quantities of items in the cart. Currently my quantity is updated as one clicks on the add item button. But as soon as I try to update the quantity by hand through a form I get an error saying the index I'm trying to pass is undefined. As I am pretty new to php I don't really know how or why it's not being passed with the value I set it to.
Now for the code:
This is my cart (the part that doesn't work properly):
<?php
if (isset($_SESSION["cart"])) {
$total = 0;
foreach(BazaKnjig::seznamVsehKnjig() as $knjiga):
if (isset($_SESSION["cart"][$knjiga->id])) {
$number = $_SESSION["cart"][$knjiga->id];
?>
<form action="<?= $url ?>" method="post">
<input type="hidden" name="do" value="update_cart" />
<input type="hidden" name="id" value="<?= $knjiga->id ?>" />
<p>
<input type="number" name="numBooks" value="<?= $number ?>" size="1"> <?= $knjiga->avtor ?>: <?= substr($knjiga->naslov, 0, 20) ?> ...
<button type="submit">Posodobi</button>
</p>
</form>
<?php
$total = $total ($knjiga->cena) * $number;
}
endforeach;
?>
<p> Skupaj: <b> <?= number_format($total, 2) ?> EUR </b></p>
I have a form to present all of the items in the cart. And when passing the variables with POST I get an error Notice: Undefined index: numBooks
. I did some googling and found that this is common when the value of the variable is empty. I am not sure if this has something to do with the fact that I'm setting the quantity with the variable $number
or if I'm missing something crucial.
And here is my code for checking the method and filtering.
if ($method == "POST") {
$validationRules = [
'do' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => [
"regexp" => "/^(add_into_cart|purge_cart|update_cart)$/"
]
],
'id' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 0]
]
];
$post = filter_input_array(INPUT_POST, $validationRules);
Then follow switch statements for the other functionalities so I will skip these as they aren't problematic and finally the update switch case:
switch($post["do"]):
case "update_cart":
$id = $post["id"];
$knjiga = BazaKnjig::vrniKnjigo($id);
$quan = $post["numBooks"];
if($quan > 0) {
$_SESSION["cart"][$id] = $quan;
} else {
unset($_SESSION["cart"][$id]);
}
break;
The error appears at $quan = $post["numBooks"];
. Any help is appreciated.
CodePudding user response:
As per Mihai's advice I added an extra filter for the 'numBooks' and that solved the issue.
CodePudding user response:
there is no
$quan = $post["numBooks"]
in your code, add that.