Notice: Undefined Variable - form processing?
I created a sample form and code below to illustrate. I know i can turn notices off in php but would rather fix the problem rather than ignore it.
When i create forms i do like what i have posted below, obviously this is just a sample with no sanitization etc.
I sort of know why i get the Notice: Undefined Variable which i know sounds dumb but not sure what's the easiest and correct way to solve it.
Could one of you great people out there show me how to stop this notice appearing?
It's only now i realised i did not have all error reporting on in WAMP and i have created allot of forms and i really don't want to be doing loads of re-editing code to fix it, hence i'm looking for a good, simple solution to solve it so i can go into all my f开发者_开发问答orms and sort it once and for all.
<?php
// check if form has been submitted
if(isset($_POST['submit'])){
// fetch form data
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
// check form fields
if(empty($name)){
$error .= 'Enter name <br />';
}
if(empty($username)){
$error .= 'Enter username <br />';
}
if(empty($email)){
$error .= 'Enter email <br />';
}
// check if errors exist
if(isset($error)){
echo $error;
} else {
// process form as normal
}
}
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<label for="name">Name:</label>
<input type="text" name="name" value="<?php if(isset($name)) echo $name; ?>" />
<label for="name">Username:</label>
<input type="text" name="username" value="<?php if(isset($username)) echo $username; ?>" />
<label for="email">Email:</label>
<input type="text" name="email" value="<?php if(isset($email)) echo $email; ?>" />
<input type="submit" name="submit" value="Send" />
</form>
You are right, the problem is the first string concatenation $error .= "something"
, because $error
does not exist before.
Easy fix: Initialise $error
with an empty string and use !empty($error)
instead of isset($empty)
.
perhaps you could simplify things:
if(isset($_POST['submit'])){
$error = "";
if(isset($_POST['name'])){
$name = $_POST['name'];
} else {
$error .= 'Enter name <br />';
}
echo $error;
}
repeat that isset() section for each var.
精彩评论