user392406
user392406

Reputation: 1323

Escaping single and double quotes while displaying dynamic text in textbox using PHP

I want to display text in html form(text field) that comes from DB so I used following code

....
.....
<input type="text" name="txtqname" id="txtqname" value="<?=$myvar ?>"></input>
....
.....

Here $myvar is variable whose value comes form DB and that may contains single or double quotes. Because of this my text is not properly displayed in text field as I want. I tried to replace double quotes with single as

....
.....
<input type='text' name='txtqname' id='txtqname' value='<?=$myvar ?>'></input>
....
.....

but still I don't get proper text. Please help me.

Thanks in advance...

Upvotes: 3

Views: 5730

Answers (4)

Billa
Billa

Reputation: 53

You can use htmlentities function with ENT_QUOTES,

Ex: htmlentities($myvar, ENT_QUOTES);

ENT_QUOTES Will convert both double and single quotes.

Upvotes: 0

Duke
Duke

Reputation: 37020

You should use proper addslashes() and stripslashes() for formatting data. Make sure every data is properly formatted before inserting into database. Also try this mysql_real_escape_string()

Upvotes: 0

Yaniro
Yaniro

Reputation: 1587

Simple, all you have to do is:

<input type="text" name="txtqname" id="txtqname" value="<?= htmlspecialchars( $myvar ) ?>"></input>

Upvotes: 8

pdu
pdu

Reputation: 10413

Just use htmlentities() or htmlspecialchars()

http://php.net/manual/de/function.htmlentities.php

Upvotes: 3

Related Questions