Using a PHP variable in a text input value = state

2019-01-23 08:37发布

I retrieve three pieces of information from the database, one integer, one string, and one date.

I echo them out to verify the variables contain the data.

When I then use the variables to populate three input boxes on the page, they do not populate correctly.

The following do not work:

id: <input type="text" name="idtest" value=$idtest>

Yes, the variable must be inside <?php var ?> for it to be visible.

So:

id: <input type="text" name="idtest" value=<?php $idtest ?> />

The field displays /.

When I escape the quotes,

id: <input type="text" name="idtest" value=\"<?php $idtest ?>\"  />

the field then displays \"\".

With single quotes

id: <input type="text" name="idtest" value='<?php $idtest ?>'  />

the field displays nothing or blank.

With single quotes escaped,

id: <input type="text" name="idtest" value=\'<?php $name ?>\'  />

the field displays \'\'.

With a forward slash (I know that's not correct, but to eliminate it from the discussion),

id: <input type="text" name="idtest" value=/"<?php $name ?>/"  />

the field displays /"/".

Double quotes, escape double quotes, escape double quotes on left side only, etc. do not work.

I can set an input box to a string. I have not tried using a session variable as I prefer to avoid do that.

What am I missing here?

6条回答
▲ chillily
2楼-- · 2019-01-23 08:51

Try something like this:

<input type="text" name="idtest" value="<?php echo htmlspecialchars($name); ?>" />

That is, the same as what thirtydot suggested, except preventing XSS attacks as well.

You could also use the <?= syntax (see the note), although that might not work on all servers. (It's enabled by a configuration option.)

查看更多
戒情不戒烟
3楼-- · 2019-01-23 08:51

If you want to read any created function, this how we do it:

<input type="button" value="sports" onClick="window.open('<?php sports();?>', '_self');">
查看更多
小情绪 Triste *
4楼-- · 2019-01-23 08:55

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 
查看更多
闹够了就滚
5楼-- · 2019-01-23 08:57

Solution

You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.

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

Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.

查看更多
成全新的幸福
6楼-- · 2019-01-23 09:00

From the HTML point of view everything's been said, but to correct the PHP-side approach a little and taking thirtydot's and icktoofay's advice into account:

<?php echo '<input type="text" name="idtest" value="' . htmlspecialchars($idtest) . '">'; ?>
查看更多
Animai°情兽
7楼-- · 2019-01-23 09:01

You need, for example:

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

The echo function is what actually outputs the value of the variable.

查看更多
登录 后发表回答