Special character (") in textfield – PHP

  php

Q(Question):

I have a value saved in mysql table like this:
{"name":"poppy"}
When I need to place another symbol " for example to name it "Cheeps and Potatoes", it’s saved in mysql table with \". Up to now all ok. This seems to me ok. Escape character added.

I restore the value twice, now…
Into a textfield in order to edit the value of name.
And also as plain value in order to view it.
As plain value, I can see the text "Cheaps and Potatoes"
but in textfield, I see void! Why ?!
I use php 5.2, mysql 5.1, and plain html.

A(Answer):

show us the section of the code that has a problem. I’m having a hard time dissecting your question.

Dan

A(Answer):

No idea what OP is asking, but make sure that magic_quotes are off are that you are properly escaping data before entering it into your database.

A(Answer):


public static function textfield($name, $value, $edit) {
if ($edit) {
print $value . "<BR/>";
$str2 = str_replace('"', "'", $value);
$str2 = ereg_replace( chr(ord("'")), "\"", $str2);
print $str2;
print( "<input id = \"$name\" name=\"$name\" type=\"text\" size=\"60px\" value=\"$str2\"/>");
} else {
print( "$value");
}
}

Above is the section I am talking about.

What is says is: If you got to edit the value, render an input of type=text. ( Please omit the lines that do str_replace as these lines with the next ereg_replace, was just my try-and-error. )

When I have a value like "Cheaps" and "Dales" for example, it is rendered quite well when NOT in edit state. But in edit state, I lose everything after (").
If I have a value, plain: Cheaps and Dales, everything is just fine.

A(Answer):

That function is… awkward. You replace quotation marks with apostrophes, and then you replace the apostrophes with quotation marks…

Get rid of the str_replace and the ereg_replace, and use htmlspecialchars() instead.

A(Answer):

O-M-G! Was that awful simple? 🙂
Sure hadn’t any clue about this function! Thank you very much Kovin!

For the record, I tried to make replacements in order to manipulate the symbols…And really it makes me a bit worry, why didn’t catch the trick….but the thing now is that it works!
Thank you!

A(Answer):

No problem.

What you were doing was escaping the quotation marks. That works in strings (such as inputting data to the database), but not in HTML. The htmlspecialchars() function converts them to HTML entities (i.e. &quot;), which is like escaping th quotes for HTML.

LEAVE A COMMENT