Page 1 of 1

How to get rid of special character/mysql_escape_string???

Posted: Mon Jun 10, 2002 11:10 am
by axel
I am a newbie and I am working with PHP 4.1.2/Mysql/Apache on MacOSX.
If a text has special characters such as an apostrophe i get an error message as soon as I want to write the text via a form into my database. I now found out that one can escape these problems by using the addslashes or the mysql_escape_string functions. I tried it, but I was not succesful and I do not exactly know where to put the function into my code. It definetly does not work this way:

$query = "INSERT INTO news_01(Headline, copy, Author, Publication, Releasedate) VALUES(mysql_escape_string('$Headline', '$copy', '$Author', '$Publication', '$Releasedate')";

Can anybody help?

Posted: Mon Jun 10, 2002 11:56 am
by twigletmac
Try something like,

Code: Select all

$query = "INSERT INTO news_01(Headline, copy, Author, Publication, Releasedate) VALUES('".addslashes($Headline)."', '".addslashes($copy)."', '".addslashes($Author)."', '".addslashes($Publication)."', '".addslashes($Releasedate)."')";
Mac

Posted: Tue Jun 11, 2002 2:00 am
by mikeq
twigletmac is correct, but I prefer this as it is easier to read and spot syntax errors

Code: Select all

$Headline = AddSlashes($Headline);
$copy = AddSlashes($copy);
$Author = AddSlashes($Author);
$Publication = AddSlashes($Publication);
$ReleaseDate = AddSlashes($ReleaseDate);

$Query = "INSERT INTO news_01(Headline, copy, Author, Publication, ReleaseDate) VALUES ('$Headline','$copy','$Author','$Publication','$ReleaseDate')";
And when you retrieve the values from your database you can use StripSlashes() function.

Posted: Wed Jun 12, 2002 4:28 am
by axel
Thanks a lot mikeq and twigletmac!

It works. But what is the difference between the addslashes and the mysql_escape_string function? I used the latter one and it works. Also why do I have to use stripslashes when retrieving data?

Posted: Wed Jun 12, 2002 4:54 am
by twigletmac
Happy to help but the best place to go when you want to know about a particular function is the manual: Basically they just escape different things.

You need to use stripslashes() when you retrieve the data to display on screen because you probably don't want to display all the escape characters.

Code: Select all

<?php
$output = addslashes("He's over there");
echo $output; // Displays -- He''s over there
$output = stripslashes($output);
echo $output; // Displays -- He's over there
?>
Mac