bind_param()中的第一个参数到底是做什么的? [英] What exactly does first parameter in bind_param() do?
问题描述
我正在尝试使用PHP和mysqli理解准备好的语句.我尝试阅读一些教程,手册和本教程: PHP中的Bind_Param ,但是我有尚未找到令人满意的答案.
I am trying to understand prepared statements using PHP and mysqli. I tried to read on some tutorials, manual and this one: Bind_Param in PHP, but I have not yet found any satisfying answer.
有人在回答中写道:
在准备SQL语句时,可以插入一个占位符(?) 列值将到达的位置,然后使用bind_param()安全地 用该占位符代替实际列的值.这样可以防止 SQL注入的任何可能性.
When you prepare an SQL statement, you can insert a placeholder (?) where a column value would go, then use bind_param() to safely substitute that placeholder for the real column's value. This prevents any possibility of an SQL injection.
我在类似这样的教程中找到了一些代码:
I found some code in tutorials like this:
$stmt = $con->prepare("INSERT INTO user_accounts VALUES (?,?,?,?)");
$stmt->bind_param('xyz', $sample1, $sample2, $sample3, $sample4); // bind to the parameter
我知道我们写的是?"而不是我们的变量,以便稍后可以提供实际值. MySQL准备执行查询的计划,然后将变量作为参数给出.
I understood that we write '?' instead of our variable, so that the actual values can be given later. MySQL prepares a plan for query execution, and then variables are given as parameters.
这行代码是什么意思?
bind_param('xyz', $sample1, $sample2, $sample3, $sample4);
四个变量都以'xyz'作为参数给出...参数'xyz'到底是什么意思?有必要写,以后再用吗?我没有发现它在其他地方使用过.
Four variables are given with something 'xyz' as parameters... What exactly does parameter 'xyz' mean here? Is it necessary to write and will it later be used? I didn't find it used elsewhere.
我只想要第一个参数的答案:
I only want an answer for the first parameter:
推荐答案
我认为您了解绑定参数的概念,因此我不再赘述.尽管如此,您可能想查看此以获取更多背景信息.
I think you understand the concept of binding parameters, so I won't go into that. Nonetheless, you might want to review this for more background information.
用于绑定参数的mysqli API可以说不是很优雅.看起来像这样:
The mysqli API for binding parameters is arguably not very elegant. It looks like this:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
这意味着该函数的第一个参数$types
为mysqli提供有关您的参数类型/应该如何对待的信息.接下来是各个参数.
This means that the first argument to this function, $types
, gives mysqli the information what types your parameters are/what it should treat them as. Following that are the individual parameters.
$types
参数是由单个字符组成的字符串,每个字符都表示一种类型.有四种可能的类型:i
,d
,s
和b
,它们代表 integer , double , string 和 binary .因此,如果要按此顺序绑定两个整数和一个字符串,则$type
参数需要为iis
.然后,按照实际值进行操作:
The $types
argument is a string of individual characters, with each character denoting a type. There are four possible types: i
, d
, s
and b
, which stand for integer, double, string and binary. So if you wanted to bind two integers and one string, in that order, the $type
parameter needs to be iis
. You then follow that by the actual values:
$int1 = 42;
$int2 = 11;
$str = 'foo';
$stmt->bind_param('iis', $int1, $int2, $str);
这篇关于bind_param()中的第一个参数到底是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!