how to escape my database content?

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
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

how to escape my database content?

Post by jasongr »

Hello

I have some string which I get from the database called $string
I need to pass this string to a javascript function like so:

Code: Select all

<a href="#" onclick="func('<?php echo $string; ?>');">test</a>
The problem here is that the string may contain any character including single or double quotes. This will cause a JavaScript error if not handled properly

I was wondering what would be the correct and robust way to escape the string so it won't interfere with string escaping in HTML and JavaScript

regards
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

urlencode would work quite well..

then use the JS function unescape() to translate it back.
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post by jasongr »

I tried you solution on the string
John Smith
and urlencode gave me
John%2C+Smith

when I invoked unescape on it I got John+Smith
How can I get rid of the '+' character that won't go away?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$string = str_replace('+','%20', urlencode('John, Smith');
Post Reply