简体   繁体   中英

How to store values with the special characters into HTML hidden fields using PHP

This may be a quite simple question but I can't figure it out. I need to store some value that contains special characters into HTML hidden fields using PHP such as 5' 5'' indicating the height of a person.

The value is stored into MySql database. I tried something like this

echo "<input type='hidden' id='ed_your_height' name='hd_your_height' 
value=".html_entity_decode($your_heigth)."/>";

and

echo "<input type='hidden' id='ed_your_height' name='hd_your_height' 
value=".htmlentities($your_heigth)."/>";

but it gives me the value 5' instead of 5' 5'' in both the cases. I need to display these values in drop down and perform some comparisons.

How can I store values with the special characters into HTML hidden field then (retrieving from database)?

Use htmlentities() and html_entity_decode() with the proper flags.

On the client-side

<input type="text name="fieldname" value="<?php echo htmlentities($string, ENT_QUOTES, 'utf-8'); ?>">

On the server-side:

$string = html_entity_decode($_POST['fieldname'], ENT_QUOTES, 'UTF-8');

Use htmlspecialchars .

value="<?=htmlspecialchars($string)?>"

Assuming short_open_tag is on (bad) or you are using PHP 5.4 (good). Otherwise, use the full <?php echo form.

PS: The reason you were having a problem in the first place is because you were not quoting your attributes - if you used the browser's View Source option you'd see the output is value=5' 5'' so it is interpreted as a value of '5 and a custom boolean attribute called 5'' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM