Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Libby

Php If Statement - Syntax Causes Form Changes

Recommended Posts

On page 92, Chapter 3, making sticky forms:

 

In this chapter a form is created with PHP used to create a text field for inputting distance.

Code then validates the content to make sure it is present and a number. The form remembers what was entered so that if an error is thrown the previous input is still there.

 

The following code is used to remember the distance entered by the user.

<?php
if (isset($_POST['distance'])) {
    echo $_POST['distance'];
}
?>

The book then remarks that this can be condensed onto one line, i.e.

<?php if (isset($_POST['distance'])) echo $_POST['distance']; ?>

but that doing so is rarely recommended.

 

In the interests of learning best practice I decided to go with the first option of splitting out the if statement. However, I noticed that this causes issues in the resulting form in that the Distance text field contains large number of extra characters which mean that the is_numeric test always fails.

This does not happen when using the if statement in a single line.

 

Given that both syntaxes are supposed to perform the same, this is somewhat puzzling and I wondered if anyone else has encountered it or found an explanation?

 

The full field creation is as follows in both syntaxes:

<p>Distance (miles): <input type="text" name="distance" value="<?php if (isset($_POST['distance'])) echo $_POST['distance']; ?> "/></p>
<p>Distance (miles): <input type="text" name="distance" value="
  <?php 
   if (isset($_POST['distance'])) {
    echo $_POST['distance']; 
   }
  ?> 
"/></p>

 

Libby

Share this post


Link to post
Share on other sites

Hello and welcome to the forums. You're getting spaces because you have spaces in your HTML before the <?php tag and after the ?> tag.

If you remove those spaces, you won't get the extra spaces in the input value.

  • Upvote 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...