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 :
- form_validation.php
<?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; } } ?>
create_ind.php
<?php require_once '../../include/connection.php'; ?> <?php require_once '../../include/form_validation.php'; ?> <?php require_once '../../include/functions_database_infoget.php'; ?> <?php $family_id = get_family_info_fam("id"); $ind_name = mysql_real_escape_string($_POST["ind_name"]); $age = validate_number(mysql_real_escape_string($_POST["age"])); $gender = $_POST["gender"]; $notes = mysql_real_escape_string($_POST["notes"]); $add_query = "INSERT INTO individual ( g_id , ind_name , age , gender , notes) Values ( {$family_id} , '{$ind_name}' , {$age} , '{$gender}' , '{$notes}')"; if(mysql_query($add_query , $connection)){ header("Location: ../../main.php"); exit; } else {echo "ERROR " . mysql_error() ; } ?> <?php mysql_close($connection); ?>add.php (a portion of my code)
<!--Main Content--> <section id="mainContent"> <header> <h3>Select where to add new Family/Individual.</h3> </header> <article> <?php if (count($errors) > 0) { for($i=0 ; $i < count($errors) ; $i++){ echo "{$errors[$i]}" . "<br/>"; } } ?> </article> </section>