Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Basics (Retired) PHP Conditionals & Loops If / ElseIf Conditionals

Frank D
Frank D
14,042 Points

If/else in a form submission

Can anyone help to solve this:

<?php 
    $name = $_POST['name'];
?>

<form method="post" action="index.php">
    <input type="text" name="name">
    <input type="submit">
</form>

<h2>Hello<?php if($name != '') { echo $name; } else { echo "buddy"; } ?> how are you today?</h2>

I have tried in many different way but I don't get why it does'nt work.

2 Answers

Jayden Spring
Jayden Spring
8,625 Points

Hi, ive refactored your code a bit to make it a bit easier to work with. The main reason it was failing is most likely your post location is different to the script either way when you are posting or getting to the same location its better to use $_SERVER['PHP_SELF'] rather than the page name (incase you change it later).

Here is what I changed your code to:

<?php
  //Print form....
  echo '<form method="POST" action="'. $_SERVER['PHP_SELF'].'">';
  echo '<input type="text" name="userName" value="Your Name Here">';
  echo '<input type="submit">';
  echo '</form>';
  //process form
  if(isset($_POST['userName']))
  {
      echo "Hello ". $_POST['userName'] ."! How are you?";
  }
  else
    echo "Please tell me your name :]";
?>

As you can see its a bit neater and has two outcomes based on if it knows someones name or not. And if you came back to change it later, its a bit easier on the eye to read rather than inline PHP everywhere.

Jayden

Frank D
Frank D
14,042 Points

Hi Jayden, your page looks a bit different from what I was aiming for, anyway your code opened my eyes to the isset() function which I have found to be very helpful in this specific case. I have now come up with this code and it seems to work perfectly as I wanted:

<?php 
    if (isset($_POST["name"])) {
      $name = $_POST['name'];
    }
?>

<form method="post" action="index.php">
    <input type="text" name="name">
    <input type="submit">
</form>

<h2>Hello <?php if(isset($name)) { echo $name; } else { echo "buddy"; } ?> how are you today?</h2>

Thanks for that ;-)