|
Posted by Malcolm Dew-Jones on 06/29/05 06:01
Ken Robinson (kenrbnsn@rbnsn.com) wrote:
: Malcolm Dew-Jones wrote:
: > Ken Robinson (kenrbnsn@rbnsn.com) wrote:
: > : You can also use urlencode($var) or htmlentities($var,ENT_QUOTES)
: > : before inserting $var into your database.
: >
: > You can, but you should still use mysql_escape_string on the result when
: > you embed it in an sql query being handled by mysql.
: You learn something new all the time. We you retrieve a string that
: was stored this way, does MySQL unescape it or is there a function to
: do it?
You do not need to unescape the string when you retrieve it later.
When you use mysql_escape_string then it ensures that no unexpected
characters in the value can corrupt the SQL command. This ensures that
the value seen by the database is the correct value, i.e. the original,
unescaped data.
e.g.
$value = "this', 'will mess things up";
$sql1 = "insert into tbl values ('$value')"; # inserts 2 columns!
$esc_value = mysql_escape_string($value);
$sql2 = "insert into tbl values ('$esc_value')"; # this is correct
If you were to now examine the contents of the database then you would see
that the second insert will have inserted a value into just one column,
and the string stored in that column will be
this', 'will mess things up
which is the original contents of the $value variable, i.e. when you
retrieve the value then you do not need to unescape it.
This has nothing to do with escaping it for html of course. If you wish
to use the value later, such as displaying it in a web page, then you
might want to escape it for that task before your use it. If you know you
are only ever going to display the data in a web page then you might wish
to do the html escaping before you save the data so that it is always
displayable in a web page with no additional steps. However, when you
save the html-escaped data in the database then you will still wish to
ensure that it is saved correctly, which is what mysql_escape_string is
for.
Often mysql_escape_string is not necessary since the data may not have any
' or ; or any other odd characters, but using it for all string values is
a good habit that will save you from unexpected problems in the future
when some one manages to enter some data that is not what you anticipated.
--
This space not for rent.
Navigation:
[Reply to this message]
|