views:

30

answers:

3

Hello all,

I think I have a URL encoding issue. I need to open a window using Javascript and pass a SQL Select query to it. So I have done this:

window.open('view_query.php?sql_query=' + query + '&db_name=' + db_name);

This has worked for me, but I have a query that breaks this:

SELECT a FROM table WHERE field like '%adhoc%' 

Now when the new window opens and I print the query received from the URL GET variable it looks like this:

SELECT a FROM table WHERE field like '�hoc%' 

Notice the bit %ad has turned into an unrecognised character! Why?

I have tried solving this with URL encoding but since I need the % symbol I can't use many URL encoders since they will turn this into something else?!

Thanks all for any help.

+2  A: 

Encode your query using http://pl.php.net/urlencode. Then decode it using http://pl.php.net/urldecode (if needed, PHP should do this for you automatically)

Piotr Pankowski
This is a Javascript issue. :)
Abs
@Abs no, it's not. Your Query is not created in JavaScript, is it?
Pekka
Tagged with PHP so I belive you have PHP available too :)
Piotr Pankowski
+1 because this also takes care of other things that could break the JS expression `"`, `'` ...
Pekka
This query is written by a user in a textarea and then passed to another script using Javascript with a window open, so PHP doesn't get to touch it. I should of explained this, apologies.
Abs
@Abs ah, okay. Then this won't work.
Pekka
A: 

This is because of url encoding - you need to call
window.open('view_query.php?sql_query='+encodeURICompoent(query)+'&db_name...);
and then on php side $query = rawurldecode($_GET['sql_query']);

cypher
Shouldn't php automatically decode values it gets in the path?
ZeissS
+2  A: 

The % character is used to encode characters in an URL using a character code. The sequence %ad means the character with the hexadecimal character code 0xAD, or decimal 173.

Use the encodeURIComponent function to escape values for the URL:

window.open('view_query.php?sql_query=' + encodeURIComponent(query) + '&db_name=' + encodeURIComponent(db_name));

Just to make sure that you (and anyone reading this) are aware of it, let me also point out the risks of sending SQL code via the browser. Anyone using the system could send anything as a query, including for example drop table.

Guffa
@Gufa - this script will be run internally and if we want to send a query to delete our database we should be shot! Do you think its better to use `escape` or `encodeURIComponent` any benefits that you know of?
Abs
@Abs `escape()` won't convert the `+` sign which will give you problems. Use `encodeURIcomponent`
Pekka
`encodeURIComponent` is UTF-8 and URL-encoding. `escape` is some random non-standard JavaScript crud that looks like URL-encoding but isn't. Don't use it.
bobince