I've build a website that will be going live soon and just have a couple questions about preventing SQL injection, I understand how to use mysqli_real_escape_string but I'm just wondering if I have to use that on all variables that I'm getting for my SQL statement and do I have to use it when I'm doing select statements also or just on insert update and delete? Also what other security would you recommend me implementing before I put the site live, thanks in advance for any help!

推荐答案

Any query can be injected whether it's read or write, persistent or transient. Injections can be performed by ending one query and running a separate one (possible with mysqli), which renders the intended query irrelevant.

Any input to a query from an external source whether it is from users or even internal should be considered an argument to the query, and a parameter in the context of the query. Any parameter in a query needs to be parameterized. This leads to a properly parameterized query that you can create a prepared statement from and execute with arguments. For example:

SELECT col1 FROM t1 WHERE col2 = ?

? is a placeholder for a parameter. Using mysqli, you can create a prepared statement using prepare, bind a variable (argument) to a parameter using bind_param, and run the query with execute. You don't have to sanitize the argument at all (in fact it's detrimental to do so). mysqli does that for you. The full process would be:

$stmt = $mysqli->prepare("SELECT col1 FROM t1 WHERE col2 = ?");
$stmt->bind_param("s", $col2_arg);
$stmt->execute();

There is also an important distinction between parameterized query and prepared statement. This statement, while prepared, is not parameterized and is thus vulnerable to injection:

$stmt = $mysqli->prepare("INSERT INTO t1 VALUES ($_POST[user_input])");

To summarize:

  • All Queries should be properly parameterized (unless they have no parameters)
  • All arguments to a query should be treated as hostile as possible no matter their source

Mysql相关问答推荐

如何将MySQL与AS&Quot;语法一起用于存储过程返回的表?

如果WHERE语句包含所有列,唯一键顺序是否重要?

对具有依赖子查询结果的2列使用等式比较来优化连接

SQL:创建新列并将现有表中的值追加到新创建的列中

在停靠容器中备份和恢复MySQL数据库时出现Unicode字符问题

默认情况下,MariaDB是否限制为本地主机?

根据时间戳分组删除

为什么我的 SQL 查询不更新 Node.js 和 MySQL 中用户以外的用户属性?

如何将多个字符串插入变量

Mysql根据文本语言或行数将列拆分为多列

如何找到每个user_id每个产品的买家类型数量?

Select 不同的列,其中另一列不包含特定值

MySQL 将分组 JSON Select 转换为单个 JSON 对象

如何解决这个特定的 SQL 查询?我的解决方案还返回不想要的值

基于 2 列的重复行的 SQL 查询

Golang Gorm 没有创建带有约束的表

如何在 Windows 上访问 xampp 的命令行

If else on WHERE 子句

Laravel classloader.php 错误打开流失败:没有这样的文件或目录

MySQL DAYOFWEEK() - 我的一周从星期一开始