Alex Rivera | Logout

How to set HTML value attribute (with spaces)

Asked 2010-06-20T04:16:14.047
22

When I use PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data.

<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = \"\""; ?> />

If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form.

Note that the $_POST["Username"] variable is correct; when I echo it using PHP, it is set to "Big Ted".

Edit
Report

2 Answers

3
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = '".$_POST["username"]' : "value = ''"; ?> />

You have to wrap the variable result with quotes, so that the browser can know what's the content of the input.

answered 2010-06-20T04:19:09.097
2

As you see its not PHP5 or even PHP question at all.
Basic HTML knowledge is obligatory for one who want to be a PHP user.

And with using templates it looks way more neat:

Getting data part code:

$username = "";
if isset($_POST['username'])) $username = htmlspecialchars($_POST["username"]);

And template code:

<input type="text" name="username" value="<?=$username?>">

If you divide your code to 2 parts it become way more supportable and readable.

answered 2010-06-20T04:26:44.350

Your Answer