开发者

Error Message function

I am trying to insert messages to a function

function addMessage($item) {
     if ($result) {
      $message =  '<p class="ok">
                    <span开发者_StackOverflow> Item added </span>
                   </p>
                  ';
                  header("Refresh: 2; url=?page=$item");
        }
        else{
            $message = '<p class=not><span>There is an error blah blah</span></p>';
        }
        return $message;

}

When I use it : addMessage('contents') it only returns to second condition. How can I fix this?


You are checking $result inside the if but its neither been assigned any value before that nor been declared as global . I think you meant to check $item:

if ($item) {


Hi jasmine

Your function always returns the second condition because you haven't assigned a value to $result, eider inside the function or when you call the function (like unicornaddict mentioned by other words).

To get your code working the way you probably want, your function should be like this:

function addMessage($item, $result) {
     if ($result) { // It will return this condition, case $result has any value assigned and is different from FALSE (boolean)
      $message =  '<p class="ok">
                    <span> Item added </span>
                   </p>
                  ';
                  header("Refresh: 2; url=?page=$item");
        }
        else{ // It will return this condition, case $result doesn't has any value assigned or is equal to FALSE (boolean)
            $message = '<p class="not"><span>There is an error blah blah</span></p>';
        }
        return $message;
}

And then you can call the function like you where already calling it, but don't forget to include a variable or a value that should be handled as the $result variable inside the function

addMessage('contents', $result);

Note:

In your $message variable you have <p class=not> and should be <p class="not">.

Remember that header() must be called before any actual output is sent to the browser.

Hope it Helps.


Is $result defined in your script? Use if ($item) instead.

Be very careful that PHP allows the usage of undefined variables.


what they said :-)

Btw, a decent IDE (like Zend) will analyze your code and warn you about things like that.

Such static code analysis is known as "linting", so google for "PHP lint" or see questions like Is there a static code analyzer [like Lint] for PHP files?

But this code sample is so small that I guess you are a beginner (no offence interned - we all had to start somewhere), so do a lot of reading and gather a lot of tools and experience.

For instance, a decent IDE (like Zend or Eclipse PDT) would let you step through your code, line nby line, and examine the value of each variable and then you ought to have seen the problem.

Welcome to PHP and good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜