-3

When I pass a variable into a PHP script I firstly check if it isset, is not blank, check that it's a string and that the length is greater than 1 and less than 255 (the DB varchar field limit) then I run it through this:

$f_name= stripslashes(htmlentities($_POST["f_name"], ENT_QUOTES));

I then use PDO prepare to update the f_name field. When I then fetch it to put it on the page I decode it like:

html_entity_decode($row["f_name"], ENT_QUOTES);

Return it in a JSON array to the AJAX call that initiated the fetch and then parse it into an input field.

If the f_name field was saved with an apostrophe in it, everything works right up to the point I try and put it in the input field with JavaScript. It just cuts off the apostrophe and anything after it. How can I stop this from happening?

var response = "<input type='text' id='f_name' value='"+rdata.patient[0].f_name+"' onkeydown='onedit(1)' maxlength='255' />";
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
user3045858
  • 57
  • 1
  • 8
  • 2
    "everything works right up to the point I try and put it in the input field with javascript" — So show us the code for that bit! – Quentin Dec 20 '16 at 12:46
  • 1
    "htmlentities / html_entity_decode" — So you make it safe to go into an HTML document before you put it into a database (why? databases are not HTML documents!) and then you make it *unsafe* to go into an HTML document before you put it into an HTML document. This doesn't make sense. – Quentin Dec 20 '16 at 12:47
  • "stripslashes" — This is only harmful unless you have magic quotes turned on (and you shouldn't because magic quotes are awful). – Quentin Dec 20 '16 at 12:47
  • Why are you using all that garbage to fetch a sanitized DB-value (as long as you use one of the `prepare`-functions in PDO, the string is sanitized) and output it? – junkfoodjunkie Dec 20 '16 at 13:45

1 Answers1

0
value='"+rdata.patient[0].f_name+"'

You are using ' characters to delimit the value of each of the attributes. If you have a ' character in the data, then it will end the attribute value. You need to represent it as &apos; instead.

A better (safer, more readable) approach would be to generate your HTML using standard DOM instead of smashing strings together.

var input = document.createElement("input");
    input.id = "f_name";
    input.value = rdata.patient[0].f_name;
    input.addEventListener("keydown", function () { onedit(1); });
    input.maxlength = 255;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335