Trouble with apostrophes in names

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
PanamaJack
Forum Newbie
Posts: 2
Joined: Mon May 17, 2010 7:56 am

Trouble with apostrophes in names

Post by PanamaJack »

I'm having problems storing names such as O ' Toole.
[*]On the 1st page the user inputs surname i.e. O ' Toole. The data is passed through to the next page (POST) as O\ ' Toole. If I just insert the data it is stored on the database as O'Toole. If I use mysql_real_escape_string() it gets stored on the database as O\' Toole. Which is the correct database storage format - should it be O\' Toole or O ' 'Toole ?

Appreciate if you can help (I've added extra spaces to show up the ')

Jackie
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Trouble with apostrophes in names

Post by pickle »

The correct method is to not store with the slash, but still use the slash in the query.

What's happening to you is magic_quotes is rearing it's head. That's a PHP directive that automatically escapes any string in $_GET, $_POST, or $_COOKIE. You want to get rid of that slash because it may not necessarily match the escaping necessary for your database.

You can do that with:

Code: Select all

$last_name = (get_magic_quotes_gpc()) ? stripslashes($_POST['last_name']) : $_POST['last_name']
That will remove any slashes that may have been added due to that directive.

You should then run the variable through mysql_real_escape_string() so it doesn't screw up your query. Your query will then look something like:

Code: Select all

INSERT
INTO
 `myTable`
 (last_name)
VALUES
 ('O\'Toole')
If you look in the database after the query, you'll see just "O'Toole" unescaped, which is what you want. Escaping a quote in a string just tells MySQL that the following character is an actual quote character, not the end of the string. The escaping character itself "\", doesn't get put in the database.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
PanamaJack
Forum Newbie
Posts: 2
Joined: Mon May 17, 2010 7:56 am

Re: Trouble with apostrophes in names

Post by PanamaJack »

Excellent - thanks for your help on this one. Response is much appreciated.
Post Reply