Reputation: 173
I am new to PHP... Just trying this simple piece of code inside my about.php file (which links to index.php file via a hyperlink):
<form action ="about.php" method="POST">
<ul>
<li>
<label for="name"> Enter your name please:</label>
<input type="text" name="name"/>
</li>
<li>
<label for="comments" rows="20"> Enter your comments :</label>
<textarea id="comments" name="comments" rows="5" cols="38">
<?php
$name = $_POST["name"];
if (!empty($name)) {
echo "Your name is ".$name."and you like ny site!";
} else {
echo "Please enter your name";
}
?>
</textarea>
</li>
<li>
<input type="submit" />
</li>
</ul>
I get the following error:
Notice: Undefined index: name in D:\xampp\htdocs\stathis1\about\about.php on line 71
Please enter your name
Upvotes: 1
Views: 247
Reputation: 2768
Right after starting your php part add this if sentence surrounding the code, so it only executes when the "name" exists.
if(isset($_POST["name"]))
Like this:
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
if (!empty($name)) {
echo "Your name is ".$name."and you like ny site!";
} else {
echo "Please enter your name";
}
} else {
echo "Please enter your name";
}
?>
Upvotes: 0
Reputation: 840
It's because $_POST['name']
hasn't been submitted/set yet. You need to either use an if statement or a ternary operator:
if (isset($_POST['name'])) {
$name = $_POST['name'];
if (!empty($name)) {
echo 'Your name is ' . $name . ' and you like ny site!';
} else {
echo 'Please enter your name';
}
}
Or, a shorter method:
$name = isset($_POST['name']) ? $_POST['name'] : '';
Upvotes: 1
Reputation:
use isset() instead of empty() because isset() function not triggering notice when the index not defined.
Upvotes: 1
Reputation: 7576
Because $_POST["name"]
is not set, you get that notice. So you need to test if it exists first, and then assign it to your $name
variable, or empty string if it's not set.
You can change
$name = $_POST["name"];
to
$name = isset($_POST["name"])?$_POST["name"]:'';
Upvotes: 1