FINAL EDIT (RESOLVED)
I just replaced if(empty($num1)) with if(!isset($num1)) and now the conditional Required! notice works flawlessly. Big thanks to everyone involved, I regained some already lost powers and I’m starting to finally make it into a fully functional, styled widget 😀 have a good day/night!
EDIT:
I have foolishly assumed that isset() is only for checkboxes…
I got rid of the Notice: Undefined index, yet the problem with Required! persists…
I have the following problem, I’ve made a calculator for product pricing, but if I load it for the first time it doesn’t “recognize” the null value in not-yet-filled-in text inputs… I’m not sure if I’m naming it right, I’m such a greenhorn when it comes to PHP, just started learning…
The form works flawlessly in general, I just want to get rid of this small problem.
Basically, I have following code:
$num1 = (int)$_POST['number1'];
$num2 = (int)$_POST['number2'];
$ratio = 0.2;
$utw = 1;
if (! empty($num1) && ! empty($num2)) {
if ($num1 * $num2 <= 200) {
$ratio = 0.2;
}
elseif ($num1 * $num2 > 200 && $num1 * $num2 < 400) {
$ratio = 0.15;
}
elseif ($num1 * $num2 >= 400) {
$ratio = 0.1;
}
if (isset($_POST['condition'])) {
$utw = 1.8;
}
$price = $num1 * $num2 * $ratio * $utw;
}
else {
$price = 0;
}
and
<form method="post" action="">
<label for="number1">
<input type="text" name="number1" id="number1">
<?php if(empty($num1)) : ?><span style="color: red;">Required!</span><?php endif; ?>
<br />Label1
</label>
<label for="number2">
<br /><input type="text" name="number2" id="number2">
<?php if(empty($num2)) : ?><span style="color: red;">Required!</span><?php endif; ?>
<br />Label2
</label>
<label for="condition">
<br /><input type="checkbox" name="condition" name="condition">
Label3<br />
</label>
<input type="submit" value="Run">
<?php if($price > 0) : ?>
<p><?php echo "Price equals: $price"; ?></p>
<?php endif; ?>
</form>
When I display it for the first time I get the
Notice: Undefined index: number1 in C:\wamp\www\calc\index.php on line 3
(line 3 because of the fact that I stripped <!doctype html> and <?php obviously)
How to avoid it? Additionally, how to ensure that the Required! notice appears only if the user clicks the submit button? Currently it is displayed since the beginning because of the fact that input fields are empty… I don’t want them “empty” I just want them, you know… visually empty or equal to 0…
I’ve worked on all of this for several hours now, have found some solutions for that PHP debug notice, but it mainly involves if (isset($var)) method, assuming I have a checkbox… Well, I don’t… The other method with default $_POST values was to actually replace
$num1 = (int)$_POST['number1'];
with:
if ($_POST['number1'] == '') {
$num1 = '0';
else {
$num1 = $_POST['number1'] ;
}
well, the notice still appears 🙁
Can anyone help me, please?
I believe isset is actually what you want; it’s irrelevant what kind of input you are using. You could write a helper function like: