PDA

View Full Version : Help with ' and " symbols



utsav
April 27th, 2009, 12:34 PM
I have a article upload form which is only accessible to the admin. Now the article may contain characters like ' or " . but when php reads these, it gives a mysql error. How do i accept these characters?

icio
April 27th, 2009, 01:04 PM
The problem is that when you form your MySQL query you have something like:

INSERT INTO `articles` (`name`, `content`) VALUES ('NAME', 'CONTENT');If you consider what happens when you have a string with ' and " characters in it, you can clearly see the query becoming malformed:

INSERT INTO `articles` (`name`, `content`) VALUES ('NAME', 'YOU'RE CONTENT AND BAD PUNCTUATION');Notice that my new "CONTENT" is now ending the string into before it should, and what follows that ended string doesn't make sense as valid SQL. To get around that, you need to escape the string that you are putting into the query.


$name = isset($_POST['name']) ? $_POST['name'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';

$query = "INSERT INTO `articles` (`name`, `content`) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($content)."'");
if (mysql_query($query)) {
echo "Success!";
} else {
echo "Problem: ", mysql_error();
}That should do the trick. See here for more approaches: http://php.net/mysql_real_escape_string

Hope that helps :thumb:

utsav
April 27th, 2009, 11:15 PM
Thanks icio

icio
April 28th, 2009, 06:00 AM
No problem