0

Why this:

$query = "SET NAMES 'utf8'";
$query = str_replace("'", "\'", $query);
$pdo->query($query);

Would cause problem?

I'm currently getting this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'utf8\''

If I don't escape it, everything's fine, but the problem exists with further queries!

MahanGM
  • 2,352
  • 5
  • 32
  • 45

2 Answers2

1

The sql you are trying to run is perfectly safe as is, it contains no user input and as such can be run without escaping.

Also you are actually escaping the delimiters of a string, not the value of the string itself.

Dale
  • 10,384
  • 21
  • 34
  • I know this, but what's the problem with it? – MahanGM Dec 10 '12 at 14:56
  • 1
    The problem (funnily enough described in the error message) is your final query looks like this `SET NAMES \'utf-8\'` which is broken, it should look like `SET NAMES 'utf-8'` – Dale Dec 10 '12 at 14:57
  • The problem is you HAVE to quote NAMES value. So if it has been escaped, it became wrong. – ozahorulia Dec 10 '12 at 14:57
1

You don't have to escape every single quote in a query, some are valid such as:

UPDATE table SET field='blah' WHERE id=10

Where field would be a varchar or similar. You would escape the quotes if they need to be part of the value of the field, such as:

UPDATE table SET field='This \'value\' uses quotes.' WHERE id=10

Hope that makes sense.

Michael
  • 402
  • 3
  • 8