1

Can someone explain what is the difference between using mysql_real_escape_string on a string or wrapping `` around the column.

For example "insert into table (``column``) values ('$string')"

or

$escapestring = mysql_real_escape_string($string);
 "insert into table (column) values ('$escapedstring')"

What is the difference between these two and what should I use? Thanks.

Samuel
  • 19
  • 1
  • 1
  • 2
  • 4
    You should probably use neither nor. Use bind parameters. That's the safest way. http://use-the-index-luke.com/sql/where-clause/bind-parameters?langtype=php – Markus Winand Apr 30 '11 at 07:25
  • Possible duplicate of [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Kzqai Sep 07 '16 at 01:34

2 Answers2

2

There's a difference between the backtick ` and the single quote '.

The backtick is intended to escape table and field names that may conflict with MySQL reserved words. If I had a field named date and a query like SELECT date FROM mytable I'd need to escape the use of date so that when MySQL parses the query, it will interpret my use of date as a field rather than the datatype date.

The single quote ' is intended for literal values, as in SELECT * FROM mytable WHERE somefield='somevalue'. If somevalue itself contains single quotes, then they need to be escaped to prevent premature closing of the quote literal.

David Weinraub
  • 14,144
  • 4
  • 42
  • 64
-1

Those two aren't related at all (as far I know anyway)

From the manual : http://php.net/manual/en/function.mysql-real-escape-string.php

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query().

So essentially what it does is, it will escape characters that are unsafe to go into mysql queries (that might break or malform the query)

So o'reily will become o\'reily

JohnP
  • 49,507
  • 13
  • 108
  • 140