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.

SOFe
  • 7,867
  • 4
  • 33
  • 61
  • Possible duplicate of [Alternative to mysql\_real\_escape\_string without connecting to DB](https://stackoverflow.com/questions/1162491/alternative-to-mysql-real-escape-string-without-connecting-to-db) – SOFe Mar 10 '18 at 13:54

2 Answers2

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.

Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30
  • 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)? – SOFe Jan 20 '16 at 11:50
  • 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?) – Franz Gleichmann Jan 20 '16 at 12:01
  • Nope. pthreads attempts to serialize an object when it is shared among threads. It is different. – SOFe Jan 20 '16 at 14:40
  • 1
    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. – Franz Gleichmann Jan 20 '16 at 14:44
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.

Community
  • 1
  • 1
Legoboy0215
  • 102
  • 2
  • 7