2

why can't I used the mysqli_escape_string function without having a database connection?

4
  • injection isn't possible without a database connection so what exactly is your question asking? Commented Jun 16, 2016 at 16:54
  • 5
    Because it's the database that knows how quote characters, etc should be escaped, not PHP; so PHP lets the database do it Commented Jun 16, 2016 at 16:55
  • updated the question Commented Jun 16, 2016 at 17:04
  • Please take a close look at my answer, especially #2 and #3. Asking this question makes me assume you are having some sort of architectural issue in your project. Feel free to comment on what it is. Commented Jun 16, 2016 at 17:18

2 Answers 2

5

From the documentation:

Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

It has to have a connection so that it knows what charset the database is using so it can use the right rules for escaping the data.

Sign up to request clarification or add additional context in comments.

Comments

3

The Answer of Quentin boils it down to an essence.

I would also like to add, that

  • As Quentin already mentioned, the charset is only known in the context of an active connection - and is essential to escaping.
  • and usually, the connection object should be available to any part of your code requiring it. Whenever you need to escape, you most likely also need to use the connection, too. If your issue is "the connection object is not reachable at this part of my code", then you should definitely work on that!
  • And please please don't try to replicate the behavior of mysqli_escape_string yourself in PHP! This only makes it potentially vulnerable to attackers. Don't assume it's as easy as to convert " to \"!

Please take a close look at #2 and #3. Asking this question makes me assume you are having some sort of architectural issue in your project.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.