How are strings escaped for each database extensio

2019-05-06 22:08发布

问题:

Before anyone jumps to conclusions as to the nature of this question, I already know about parameterized/prepared statements and use them whenever possible. Unfortunately, it is not always possible to use them when building dynamic queries.


I'm interested in working with databases other than MySQL, but I can't easily find good sources as to how to escape strings for each database extension to prevent SQL Injection.

The PHP docs list the following vendor specific database extensions. I've boldened the ones I'm most interested in:

  • CUBRID
  • dBase
  • DB++
  • FrontBase
  • filePro
  • Firebird/InterBase
  • Informix
  • IBM DB2
  • Ingres
  • MaxDB
  • Mongo
  • mSQL
  • Mssql
  • MySQL
  • Mysqli
  • Mysqlnd
  • mysqlnd_ qc
  • OCI8
  • Ovrimos SQL
  • Paradox
  • PostgreSQL
  • SQLite
  • SQLite3
  • Sybase
  • tokyo_ tyrant

Example of dynamic query that wont work for most parameterized statements:

"Select $col1, $col2 from $table where $col1 = ?"

After $col1, $col2, and $table have been escaped, the statement can be used in a prepared statement.

回答1:

PostgreSQL and others (PDO)

PostgreSQL can use pg_escape_string for string escaping.

For PostgreSQL you don't need any escaping thanks to pg_query_params()

Besides that, you should use PDO with prepared statements. They take care of it and you can pass arguments separately; just like with pg_query_params()



回答2:

MongoDB

In MongoDB you do not write SQL but work with objects ("documents") - you don't have to escape things as you never use strings except for data.

However, you do need to ensure that you actually pass strings and not arrays to the MongoDB API. At least in PHP passing an array such as array('$ne' => 1) would result in an != 1 check and thus be similarly dangerous as SQL injection. And unfortunately PHP allows the client to create arrays inside $_POST etc. by simply providing a field with a name using the PHP array syntax such as password[$ne]. [Source]



回答3:

MySQL

Use mysql_real_escape_string.



回答4:

MySQLi

Use mysqli_real_escape_string.



回答5:

OCI8

As far as I can tell:

function oci_escape_string( $str )
{
  return strtr( $str, array( "'" => "''" ) );
}

Should do the trick, ignoring wildcard chars for LIKE statements.



回答6:

CUBRID

According to its manual, CUBRID PHP API has the same syntax as MySQL, i.e. cubrid_real_escape_string. With its new CUBRID 8.4.0 release it provides 90% compatibility with MySQL.