redconservatory
redconservatory

Reputation: 21924

MySQL SELECT * WHERE name = "something with a backslash \"

I have a table

table_id | name   | amount
1        | Arby\'s| 12
2        | Wendy's| 8

I usually do a

SELECT * WHERE table_id = whatever

But I would like (instead) do:

SELECT * WHERE name = "Arby\'s";

However, I seem to be running into problems with the backslash. The result isn't showing up at all. I've also tried

SELECT * WHERE name = 'Arby's;

Without any luck.

Is there any way to search by name if the name contains apostrophes or other special characters (ampersands etc?)

Upvotes: 3

Views: 22007

Answers (3)

Fad
Fad

Reputation: 9858

If you're on PHP, you can use mysql_real_escape_string()

You might also want to look at this How do I escape special characters in MySQL?

Upvotes: 1

DaveRandom
DaveRandom

Reputation: 88667

 SELECT * WHERE name = 'Arby\'s'; 

You're missing a closing ' on the end of your string. That will match Arby's. If you wanted to match Arby\'s (which I don't think you do) it would be:

 SELECT * WHERE name = 'Arby\\\'s'; 

Back slashes need to be 'double escaped', as it were, because they are the escape character. So to match \\ your query needs to be \\\\. When they immediately precede another character that needs to be escaped, you end up with another one - so to match \\' you need \\\\\'

I suggest you read this.

Upvotes: 1

Jacob
Jacob

Reputation: 43229

SELECT * FROM table WHERE name = 'Arby\\\'s'

Escape the backslash with a backslash and escape the apostrophe with another backslash leads to 3 backslashes.

Upvotes: 2

Related Questions