Apostrophe in MySQL

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
UMGuide
Forum Newbie
Posts: 2
Joined: Tue Jan 27, 2009 10:53 am

Apostrophe in MySQL

Post by UMGuide »

When inserting information into a MySQL database via PHP I have had it where when there is an apostrophe, I have to escape it by making it double apostrophe. Below is an example of the code I use:

$message = "5'00";
$message = str_replace("'", "''", $message);
mysql_query("INSERT INTO dbtable (field) VALUES('".$message."')");

And that works fine for most hosts. But, there are some hosts where if I have 2 apostrophes it doesn't work. For those hosts, they don't have a problem with the apostrophe and the code I use looks like the example below:

$message = "5'00";
// $message = str_replace("'", "''", $message);
mysql_query("INSERT INTO dbtable (field) VALUES('".$message."')");

So, this has been my problem, as the code I write works on 1 host but not another. I've been writing scripts that are installed on several hosts, and I need a solution where the code I write works on every host. Is there an "apostrophe solution" so that hosts that require the double apostrophe are happy and hosts that don't need it also work?

THANKS!!!!!!!!!!!!!!!!!!!!!!
Chris
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Apostrophe in MySQL

Post by mattpointblank »

There's a php function called addslashes() that does what you want. Read up on it!
pl_towers
Forum Newbie
Posts: 12
Joined: Tue Jan 27, 2009 12:59 pm

Re: Apostrophe in MySQL

Post by pl_towers »

if i understand your problem try mysql_real_escape_string() to protect your sql statements
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Apostrophe in MySQL

Post by John Cartwright »

mattpointblank wrote:There's a php function called addslashes() that does what you want. Read up on it!
addslashes() is not advisable because it actually manipulates the data instead of simply escaping it for the query. mysql_real_escape_string() escapes much more than simply quotes (which are listed in the manual).
Post Reply