1

I am not asking how to use the function.

I know what the function mysqli_real_escape_string is about or how to use it, but I want to ask, why does its first argument require a reference to a mysqli connection?

Here are some guesses, but I don't know if I guessed correctly:

  • Does the function trigger any calls to the database connection such that it requires a connection to escape the string with?
  • Is this some technical constraint in the PHP implementation?
  • Or any other reasons?

This problem is troubling me because I have multithreading in my software, and I have a function that accepts a string query as parameter and pushes the query to another thread to execute, so I can't get an instance of MySQLi to escape strings in my query with.

1

2 Answers 2

2

From http://php.net/manual/de/mysqli.real-escape-string.php : mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

so in short: the function has to know what charset your connection uses.

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

4 Comments

I edited the question; please read the last paragraph. Is it possible to escape a MySQL query without having an instance of mysqli (at least in the current thread)?
threads do not have separate memory space. you CAN access thread#1's mysqli-instance from thread#2 - and as long as you don't actually use it for anything but escaping, there should not be any sort of problem - have you tried that? else you could just instanciate a dummy-instance just for escaping. (one could also wonder why one would escape data for a mysql-connection without having a mysql-connection?)
Nope. pthreads attempts to serialize an object when it is shared among threads. It is different.
okay, didn't know that - never done anything in php-pthreads before except preventing the need to fork. then the still-remaining options are the dummy-instance and escaping in the thread where the escaped string is needed, e.g. where there already is a connection.
1

Alternative to mysql_real_escape_string without connecting to DB

This basically explains why. The has to know what char set the MySQL connection uses. If you don't, multi-byte SQL injections may be possible, depending on your code. Anyways, you are required to use a MySQL instance unless you write your own function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.