I'm trying to output some text stored in a variable in my HTML file
<span class="error">*<?php echo $piIdError;?></span>
I have declared and initialized the variable already along with the rest of some other php code that works
if (empty($_POST['piId']))
{
$piIdError = "Pi Id is Required";
}
else
{
$id = $_POST['piId'];
}
but when I run the file I get this error:
Notice: Undefined variable: piIdError in C:\xampp\htdocs\piWebConfig\index.php on line 86
Anyone have any ideas to what might be happening?
Thanks
Just initialize the variable $piIdError
with the default value like
$piIdError = '';
if (empty($_POST['piId']))
{
$piIdError = "Pi Id is Required";
}
else
{
$id = $_POST['piId'];
}
Because if the condition failes then it goes for the else
part at where the $piIdError
was not defined.Orelse you can use isset
like
<span class="error">*
<?php if(isset($piIdError))
echo $piIdError;?>
</span>
In your HTML code, use isset()
to check if the variable is declared. You can pair it with a ternary operator, and you're all set:
<span class="error"><?php echo (isset($piIdError)) ? $piIdError : ''; ?></span>
<?php
if ($_POST['piId'] == '') {
$piIdError = "Pi Id is Required";
} else {
$id = $_POST['piId'];
}
?>
<?php
if(isset($piIdError)) {
echo '<span class="error">*'.$piIdError.'</span>';
}
?>