PHPLOVER PHPLOVER - 7 months ago 32
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.

// check if form has been submitted

// fetch form data
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];

// check form fields
$error .= 'Enter name <br />';
$error .= 'Enter username <br />';
$error .= 'Enter email <br />';

// check if errors exist
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" />



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