Dealing with quotes in input values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pmorg
Forum Newbie
Posts: 2
Joined: Wed May 05, 2010 12:48 pm

Dealing with quotes in input values

Post 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?
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Dealing with quotes in input values

Post by flying_circus »

Code: Select all

<?php
  $title = "Isn't this a problem?";
  echo "<input type-text name=title value='" . htmlspecialchars($title, ENT_QUOTES) . "'>";
?>
pmorg
Forum Newbie
Posts: 2
Joined: Wed May 05, 2010 12:48 pm

Re: Dealing with quotes in input values

Post 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.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Dealing with quotes in input values

Post 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?)
Post Reply