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 variables inside form input values.

Can I use php variables inside form input values something like this.

<form method="POST" action="account_profile.php?r=update">
<input type="text" name="name" id="name" value="<?php echo $name; ?>">
<input type="email" name="email" id="email" value="<?php echo $email; ?>" disabled>
<input type="text" name="bitcoin" id="bitcoin" value="">
<input type="text" name="perfectmoney" id="perfectmoney" value="">
<input type="text" name="egopay" id="egopay" value="">
<input type="submit" value="Update Account">
</form>

3 Answers

Yes you can

Make sure you escape any output that could potentially come from a user (if this is what you're planning on doing). An example would be maintaining the form values between pages, like when you have an error in the submission and you don't want the user to lose the correct/previous information they've entered.

A really simple example of escaping would be:

<?php

value="<?php echo htmlspecialchars($_POST['email']); ?>"

?>

You can test it out by not escaping the output and entering php code directly into the input.. You can really mess things up!

In my opinion, even better and definitely shorter way to do it is to ommit 'php' and 'echo' and use shortened PHP opening brackets for echo. Here is an example:

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

is equal to:

<input type="text" name="first_name" value="<?php echo $first_name; ?>">