Reputation: 614
function checkInputs()
{
$fname = $_POST["fname"];
$lname = $_POST['lname'];
$email = $_POST['email'];
...
}
<form method = 'POST' action = 'index.php'>
First Name:<input type = 'text' name = 'fname'>
Last Name:<input type = 'text'name = 'lname'>
Email:<input type = 'text' name = 'email'>
</form>
The function isn't called until a button is clicked.
Regardless I've tried putting the php tag after the page loads and regardless it still produces the error 'Undefined index : ... at Line
Upvotes: 0
Views: 1515
Reputation: 10214
You need to check if the value exists first before trying to use it
If someone left the fname field blank and submitted your form then it would not be set in the $_POST var
$fname = isset($_POST["fname"]) ? $_POST["fname"] : NULL;
if ($fname == NULL) {
echo "First name is required";
}
Upvotes: 1
Reputation: 360602
If you haven't wrapped that code in appropriate method checks, it'll run every time the page is loaded, whether a form has been submitted or not, e.g.
<?
function checkInputs() { blah blah blah }
checkInputs();
?>
<form ...>
...
</form>
will execute your checkInput function when the form is loaded AND when it's submitted. When the form is first loaded via get, $_POST will be empty (since the page was requested via a GET call), and you'll get those errors.
But if you have:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
checkInputs();
}
then your check function will only run when the script was invoked via a POST request.
Upvotes: 0