rafael
rafael

Reputation: 687

PHP variable scope question

I'm a beginner to PHP and trying to write a code, that does form validation. It's nothing fancy just testing it out. I just wrote a function that test the Age input text whether it's a number or not. If it isn't it stores an error in an array and then display that error in another page. I saw this method in a video tutorial , but couldn't do it myself. When i try to invoke that error (not numeric value in Age) it always shows me this error in my add.php page :

Notice: Undefined variable: errors in /home/rafael/www/RofaCorp/add/add.php on line 37

How do i declare a variable that can be accessed through my whole project ?

Here's my code :

<?php

function validate_number($number) {
   global $errors;
   if (is_numeric($number)) {
       return $number;
   }else {
       $errors[] = "Value must be number";        
   }

   if (!empty ($errors))
   {
       header("Location: ../add.php");
       exit;
   }
}

?>

Upvotes: 0

Views: 213

Answers (2)

frostymarvelous
frostymarvelous

Reputation: 2805

If it is shown in another page, use sessions. Will allow you to retrieve variables from other pages.

You can use this simple tut http://www.tizag.com/phpT/phpsessions.php

Upvotes: 1

jeroen
jeroen

Reputation: 91742

A global variable is only defined while your scripts are processing, as soon as you do header("Location: ../add.php"); you are loading a new page and all variables are lost. That´s what the error message is telling you, there is no variable $errors in add.php.

If you want your error message to persist between different page loads, a session variable is a good option (there are of course others like databases, etc.). Just start the session again in add.php and you have access to the variables stored in the session.

Upvotes: 3

Related Questions