bind_param()仅对用户输入的值或全部必需? [英] bind_param() only necessary on user-inputted values or all?

查看:116
本文介绍了bind_param()仅对用户输入的值或全部必需?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读SQL注入,但是找不到这个问题的答案.

I've been reading up on SQL injections and I couldn't find an answer to this question.

我知道我是否会这样查询

I understand if I a query like this

prepare("SELECT id, foo, bar FROM table WHERE username = ?");

然后我应该使用bind_param('s', $username)以避免SQL注入的可能性.

Then I should use bind_param('s', $username) to avoid SQL injection possibilities.

但是,如果我在不是用户输入但是自动生成的ID之类的内容上运行查询,该怎么办?示例:

But what if I running my query on something that is not user-inputted but something like an auto-generated ID. Example:

prepare("SELECT username, foo, bar from table where id = ?");

其中id是自生成的(自动增加的值).我是否也必须在这里使用bind_param('i', $id)还是可以将查询准备为:

Where id is self-generated (auto-incremented value). Do I have to make use of bind_param('i', $id) here too or can I just prepare the query as:

prepare("SELECT username, foo, bar from table where id = '$id'");

如果需要bind_param();,为什么?

谢谢!

推荐答案

从技术上讲,如果您不准备并非来自用户输入的数据,则不会受到威胁.但是,强烈建议您这样做,原因有两个:

Technically you're not at risk if you don't prepare data that's not coming from user input. However, it's strongly advised to do so for a couple of reasons:

  1. 如果您忘记在某处准备任何用户输入数据,则该用户有可能将一些其他内容注入到您从未希望成为用户输入的数据行中.
  2. 重复执行您的操作以确保服务器安全是一个好习惯.如果您开始对其进行混合,那么您很可能会忘记在实际需要的地方准备数据.
  3. 准备数据并不仅仅是为了防止攻击者进行SQL注入.如果您不小心在代码中创建了错误,它还可以防止某些数据库问题.例如:

在代码中的某些地方,您有一个日志系统,该日志系统将错误日志添加到数据库中.字符串为:

Somewhere in your code you have a log system that adds an errorlog to your database. The string would be:

错误:IP为"x.x.x.x"的用户"xxx"使用了错误的密码.

Error: User "xxx" with IP "x.x.x.x" used a wrong password.


该字符串由您的脚本生成.因此,您无需准备.但是,该字符串中的引号会引起数据库错误,如果您仍然准备它,可以避免该错误.


This string is generated by your script. Therefor you don't prepare it. Yet the quotes inside this string will cause errors with your database that could've been prevented if you prepared it anyway.

这篇关于bind_param()仅对用户输入的值或全部必需?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆