如何防止在LAMP应用程序中进行SQL注入?

问题描述:

以下是开始对话的几种可能性:

Here are a few possibilities to get the conversation started:

  1. 在初始化时转义所有输入.
  2. 最好在生成SQL时转义每个值.

第一个解决方案是次优的,因为如果要在SQL以外的其他任何方式中使用每个值,则需要取消转义每个值,例如将其输出到网页上.

The first solution is suboptimal, because you then need to unescape each value if you want to use it in anything other than SQL, like outputting it on a web page.

第二种解决方法更有意义,但是手动转义每个值是一件痛苦的事情.

The second solution makes much more sense, but manually escaping each value is a pain.

我知道准备的语句,但是我发现

I'm aware of prepared statements, however I find MySQLi cumbersome. Also, separating the query from the inputs concerns me, because although it's crucial to get the order correct it's easy to make a mistake, and thus write the wrong data to the wrong fields.

正如@Rob Walker所说,参数化查询是最好的选择.如果您使用的是最新最好的PHP,我强烈建议您查看 PDO (PHP数据对象).这是一个本机数据库抽象库,它支持各种数据库(当然包括MySQL)以及带有命名参数的准备好的语句.

as @Rob Walker states, parameterized queries are your best bet. If you're using the latest and greatest PHP, I'd highly recommend taking a look at PDO (PHP Data Objects). This is a native database abstraction library that has support for a wide range of databases (including MySQL of course) as well as prepared statements with named parameters.