php - bind_param() 中的第一个参数到底做了什么?

标签 php mysql mysqli prepared-statement bindparam

我正在尝试使用 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”在这里究竟是什么意思?有没有必要写,以后会不会用到?我没有发现它在其他地方使用过。

我只想要第一个参数的答案:

enter image description here

最佳答案

我想您了解绑定(bind)参数的概念,所以我不会深入探讨。尽管如此,您可能想要查看 this了解更多背景信息。

用于绑定(bind)参数的 mysqli API 可以说不是很优雅。它看起来像这样:

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

这意味着此函数的第一个参数 $types 向 mysqli 提供了您的参数是什么类型的信息/它应该如何对待它们。接下来是各个参数。

$types 参数是一个由单个字符组成的字符串,每个字符表示一种类型。有四种可能的类型:idsb,代表整数 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/

相关文章:

php - mysqli query select 例如notification query select from 4 other tables which are constrained by a certain key value and return a singular result

php - 准备好的语句: num_rows is always zero

javascript - 通过简单的html dom删除页面的所有href

PHP/MySQL 登录表单

mysql - 为一个非常简单的网站设计一个更复杂但灵活的数据库设计是否值得?

php - 一对多和一对多关系 laravel

mysql - 字符串运算符在 Sequelize 中不可用

PHP MySQL : Count number of elements that are not present in another table

php - 如何在 PHP 中获取访问者的时区?

javascript - 当在另一个 php 文件中插入某些数据时,使用 ajax 在 php 页面的 div 中加载内容