Page 1 of 1

Dealing with quotes in input values

Posted: Wed May 05, 2010 1:08 pm
by pmorg
I often write editors for data stored in mySQL. A user selects the row they want to edit and my programs write a form with the results of the SQL preloaded in the fields so the user can edit them. As an example there may be a line in my code like:

Code: Select all

echo”<input type=text name=title value='$title'>”;
Here's the problem... If $title includes text containing a single quote the value the output is something like:
<input type-text name=title value='Isn't this a problem?'>
which truncates the value of $title to:
Isn
Not good.

There must be some way around this which I haven't figured out, or found.

Suggestions?

Re: Dealing with quotes in input values

Posted: Wed May 05, 2010 1:41 pm
by flying_circus

Code: Select all

<?php
  $title = "Isn't this a problem?";
  echo "<input type-text name=title value='" . htmlspecialchars($title, ENT_QUOTES) . "'>";
?>

Re: Dealing with quotes in input values

Posted: Sat May 08, 2010 1:23 pm
by pmorg
Thanks...that solved the problem I asked about, however, it also just pushed the problem on to the next step. When the edited values were used to UPDATE the db that command had problems with the quotes too. Oddly enough INSERT did not, so I combined DELETE and INSERT to effectively update the file and all is well.

Re: Dealing with quotes in input values

Posted: Sat May 08, 2010 2:48 pm
by Apollo
htmlspecialchars is used to include your string in html, which is something entirely different than SQL queries.

If $s is some user input (possibly containing quotes, backslashes and whatnot), use mysql_real_escape_string($s) before using it in SQL queries. For example:

Code: Select all

$s = $_POST['name'];
$s2 = mysql_real_escape_string($s);
mysql_query("UPDATE fanclub SET name='$s2' WHERE id=16"); // using $s instead of $s2 here would be wrong!
This ain't just to avoid problems with quotes, but also for security reasons (to prevent injection hacks, otherwise guess what would happen if some bozo enters "x'; DROP TABLE fanclub;" as his name?)