0

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

8
  • 3
    Show us where you initialized the $piIdError Commented Dec 10, 2014 at 12:37
  • Can you include the while file so that we can see where piIdError is defined? Commented Dec 10, 2014 at 12:37
  • 1
    One line of code isn't enough to properly diagnose the problem. The notice doesn't lie. Commented Dec 10, 2014 at 12:37
  • 1
    How can he show where he define variable, if it undefined? :) Commented Dec 10, 2014 at 12:38
  • 1
    Just write on top of file $piIdError = ""; Commented Dec 10, 2014 at 12:40

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

@vp_arth may be it represents required field.
error class can be both required and error messages..they both represent in red.
0

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>

Comments

0
<?php
if ($_POST['piId'] == '') {
    $piIdError = "Pi Id is Required";
} else {
    $id = $_POST['piId'];
}
?>

<?php
if(isset($piIdError)) {
    echo '<span class="error">*'.$piIdError.'</span>';
}
?>

2 Comments

What language you use here? It's not valid php
you should split html from php here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.