views:

35

answers:

3

I've been wondering for the longest time WHY I actually need a live resource to SQL connected in order to use mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )

Does this function not simply escape the data? What's the point of connecting? I want to use the function without a connection, I'm debating creating an account with no privileges just so I can do this.

I call a wrapper function runSQL(user, statement) and return an array with either the data or boolean status.

I've been thinking of making this runSQL(user, statement, arguments-and-validation-data)

I just want a reason. I can't find a "why" on the man page.

+4  A: 

Correct escaping depends in part on the current connection's character set, so it needs to know that information about a live connection.


Re your comment, here's a link to the manual for MySQL's C API, which is used by the PHP function:

http://dev.mysql.com/doc/refman/5.1/en/mysql-real-escape-string.html

It says:

Note that mysql must be a valid, open connection. This is needed because the escaping depends on the character set in use by the server.

Bill Karwin
Could you provide me a link to a doc on this?
+4  A: 

From the documentation for mysql_real_escape_string - http://php.net/manual/en/function.mysql-real-escape-string.php

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query()

mluebke
That's what I was looking for. Thank you.
Bonus round: Is there a way I could do this without being connected?
Not using the `mysql` extension, no. Please consider using something more modern, like PDO or even `mysqli`.
Charles
I agree with the recommendation of PDO for its additional features, but it doesn't remove the requirement to be connected while using the escaping/quoting function. All the MySQL extensions in PHP use the same MySQL C API.
Bill Karwin
A: 

It's possible to open multiple MySQL connections at a time. Usually you omit the resource parameter because you only use 1 MySQL connection in your script, and it defaults to the last opened connection.

casablanca