Hey, I'm a novice at PHP, so have mercy on me!
I'm trying to echo $qty, but it's saying that the variable is an undefined variable.
If you see anything I'm doing wrong, feel free to tell me!
Thanks in advance!
action.php:
foreach ($rows as $row){
$food = $row['food'];
$price = $row['price'];
if(isset($_POST['qty'])){
$qty = $_POST['qty'];
echo 'set';
}else{
echo 'unset';
}
echo "<tr>
<td>$food</td>
<td>$qty</td>
<td>$price</td>
</tr>";
}
order.php:
foreach ($rows as $row) {
$food = $row["food"];
$price = $row["price"];
$picture = $row["picture"];
$description = $row["description"];
$id = $row['id'];
echo "<tr>
<td><img src='$picture' width='120px' /></td>
<td>$food</td>
<td>$$price</td>
<td><input type='number' min='0' max='10' placeholder='#' name='qty' maxlength='1'></td>
</tr>";
}
It seems almost certain then that if(isset($_POST['qty'])){
didn't pass, so the variable wasn't given a value. Make sure you are passing POST data to this script
If I am correct, you should see the word "unset" in the output.
You could set $qty
in advance so that no matter what, it will have a value, or give it a different value if your if
statement is false:
//set a default value earlier
$qty = 'This is the default value!';
//or in the if statement
if(isset($_POST['qty'])){
$qty = $_POST['qty'];
echo 'set';
} else {
$qty = 'qty wasn't given a value!';
echo 'unset';
}
It's not defined because you're not POSTing(form submission) a field named qty
You're trying to use $qty
when it isn't set. This occurs when $_POST['qty']
is empty. What you need to do is set a default value for it in those cases:
if(isset($_POST['qty'])){
$qty = $_POST['qty'];
}else{
$qty = 0;
}
Or use the ternary operator to make this a one-liner:
$qty = (isset($_POST['qty'])) ? $_POST['qty'] : 0;