1

I can't seem to apply the $_POST function properly to retrieve the data from a simple HTML form. I'm new to PHP, so I may be overlooking something simple.

I have a form with action directing to the same page, but if the form is filled out, the value of $_POST['input_name'] will have changed, so I can trigger the php function using that condition. Is this the best way to structure this kind of action?

Here's my HTML code (thispage.php is the current/same page):

<form action="thispage.php" method="post">
  Name: <input type="text" name="userName" id="userName" />
  <input type="submit" />
</form>

Here's my PHP code from the same page:

if("" == trim($_POST['userName'])){
  echo $_POST['userName'];
}

Thanks a lot in advance!!

2
  • 2
    If the posted value equals an empty string then what exactly do you expect to see from that echo statement? Commented Nov 16, 2015 at 11:43
  • 2
    STYLE ONLY POINT: username does not have camelCase in it as it is a recognised word in the Oxford English Dictionary Commented Nov 16, 2015 at 11:50

5 Answers 5

4

First remove the action from form if your server side code is in the same page. And Use the empty() or isset() functions for checking the value.

For Example:

if(!empty(trim($_POST['userName']))){
  echo $_POST['userName'];
}

if(isset(trim($_POST['userName']))){
  echo $_POST['userName'];
}
Sign up to request clarification or add additional context in comments.

Comments

2
if("" == trim($_POST['userName'])){
  echo $_POST['userName'];
}

This is actually checking if the value is empty and echoes it if it is.

You probably want to use !empty($_POST['userName']) to check if it's not empty and then echo it if it is not.

Comments

2

try this:

HTML code

<form action="thispage.php" method="post">
  Name: <input type="text" name="userName" id="userName" />
  <input type="submit" name="submit" />
</form>

PHP code on the same page:

if(isset($_POST['submit']))
{
    if(isset(trim($_POST['userName']))){
        echo $_POST['userName'];
    }
}

Comments

1

Try this...

if(trim($_POST['userName']) != ' '){
    echo $_POST['userName'];
}

Comments

1

you can try it:

if(isset($_POST['userName'])){
 $name = $_POST['userName'];
 echo $name;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.