Thomas Hutton Thomas Hutton - 6 months ago 16
PHP Question

Undefined Index Errors User Input

I'm just relearning PHP, except it's OOP this time.

So I'm doing my classes/functions lesson and I decided to try my hand at a user-inputted function and echo at that information.

My code:

<?php

$f_name = $_POST['firstname'];
$l_name = $_POST['lastname'];
$agee = $_POST['age'];
$name = new Person($f_name, $l_name, $agee);

class Person {

var $first_name;
var $last_name;
var $age;

function __construct($firstName, $lastName, $myAge) {

$this->first_name = $firstName;
$this->last_name = $lastName;
$this->age = $myAge;

echo "My name is $firstName $lastName, and my I'm $myAge years old.";

}

}

?>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inserting</title>
</head>
<body>
<form action="enteredfunction.php" method="post" autocomplete="off">
<input type="text" name="firstname" placeholder="First name">
<input type="text" name="lastname" placeholder="Last name">
<input type="text" name="age" placeholder="Age">
<input type="submit" value="Insert">
</form>
</body>
</html>


And I get the following errors:

Notice: Undefined index: firstname in C:\xampp\htdocs\ooptutorial\classes\enteredfunction.php on line 3

Notice: Undefined index: lastname in C:\xampp\htdocs\ooptutorial\classes\enteredfunction.php on line 4

Notice: Undefined index: age in C:\xampp\htdocs\ooptutorial\classes\enteredfunction.php on line 5
My name is , and my I'm years old.


I know what my error is, but I'm not sure what to do for it.

Any help would be appreciated.

Answer

Check if it's empty first

if (
  !empty($_POST['firstname']) &&
  !empty($_POST['lastname']) &&
  !empty($_POST['agee'])
){
$f_name = $_POST['firstname'];
$l_name = $_POST['lastname'];
$agee = $_POST['age'];
$name = new Person($f_name, $l_name, $agee);
}