PHPLOVER PHPLOVER - 5 months ago 10
PHP Question

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 forms 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>

Answer

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).