我正在尝试使用 PHP 和 mysqli 理解准备好的语句。我试着阅读一些教程、手册和这个:Bind_Param in PHP ,但我还没有找到任何令人满意的答案。
有人在回答中写道:
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.
我在这样的教程中找到了一些代码:
$stmt = $con->prepare("INSERT INTO user_accounts VALUES (?,?,?,?)");
$stmt->bind_param('xyz', $sample1, $sample2, $sample3, $sample4); // bind to the parameter
我明白我们写'?'而不是我们的变量,以便稍后可以给出实际值。 MySQL 准备一个查询执行计划,然后将变量作为参数给出。
这行代码是什么意思?
bind_param('xyz', $sample1, $sample2, $sample3, $sample4);
四个变量以“xyz”作为参数给出……参数“xyz”在这里究竟是什么意思?有没有必要写,以后会不会用到?我没有发现它在其他地方使用过。
我只想要第一个参数的答案:
最佳答案
我想您了解绑定(bind)参数的概念,所以我不会深入探讨。尽管如此,您可能想要查看 this了解更多背景信息。
用于绑定(bind)参数的 mysqli API 可以说不是很优雅。它看起来像这样:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
这意味着此函数的第一个参数 $types
向 mysqli 提供了您的参数是什么类型的信息/它应该如何对待它们。接下来是各个参数。
$types
参数是一个由单个字符组成的字符串,每个字符表示一种类型。有四种可能的类型:i
、d
、s
和 b
,代表整数、 double 、字符串 和二进制。因此,如果您想按顺序绑定(bind)两个整数和一个字符串,$type
参数需要为 iis
。然后您按照实际值进行操作:
$int1 = 42;
$int2 = 11;
$str = 'foo';
$stmt->bind_param('iis', $int1, $int2, $str);
关于php - bind_param() 中的第一个参数到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826489/