我想看一个例子,说明如何使用bind_resultget_result来调用,以及使用其中一个来替代另一个的目的是什么.

还有使用每种方法的利弊.

使用这两种方法的限制是什么,有什么不同吗?

推荐答案

尽管这两种方法都适用于*个查询,但当使用bind_result()时,列通常会在查询中显式列出,因此在bind_result()中分配返回值时可以参考列表,因为变量的顺序必须严格匹配返回行的 struct .

Example 1 for $query1 using bind_result()

$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$id = 5;

$stmt = $mysqli->prepare($query1);
/*
    Binds variables to prepared statement

    i    corresponding variable has type integer
    d    corresponding variable has type double
    s    corresponding variable has type string
    b    corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);

/* execute query */
$stmt->execute();

/* Store the result (to get properties) */
$stmt->store_result();

/* Get the number of rows */
$num_of_rows = $stmt->num_rows;

/* Bind the result to variables */
$stmt->bind_result($id, $first_name, $last_name, $username);

while ($stmt->fetch()) {
    echo 'ID: '.$id.'<br>';
    echo 'First Name: '.$first_name.'<br>';
    echo 'Last Name: '.$last_name.'<br>';
    echo 'Username: '.$username.'<br><br>';
}

Example 2 for $query2 using get_result()

$query2 = 'SELECT * FROM `table` WHERE id = ?'; 
$id = 5;

$stmt = $mysqli->prepare($query2);
/*
    Binds variables to prepared statement

    i    corresponding variable has type integer
    d    corresponding variable has type double
    s    corresponding variable has type string
    b    corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);

/* execute query */
$stmt->execute();

/* Get the result */
$result = $stmt->get_result();

/* Get the number of rows */
$num_of_rows = $result->num_rows;

while ($row = $result->fetch_assoc()) {
    echo 'ID: '.$row['id'].'<br>';
    echo 'First Name: '.$row['first_name'].'<br>';
    echo 'Last Name: '.$row['last_name'].'<br>';
    echo 'Username: '.$row['username'].'<br><br>';
}

bind_result()

Pros:

  • 适用于过时的PHP版本
  • 返回单独的变量

Cons:

  • 所有变量都必须手动列出
  • 需要更多代码才能将行作为数组返回
  • 每次更改表 struct 时,都必须更新代码

get_result()

Pros:

  • 返回关联/枚举数组或对象,自动填充返回行中的数据
  • 允许fetch_all()方法一次返回所有返回的行

Cons:

  • 需要MySQL本机驱动程序(mysqlnd)

Php相关问答推荐

如何以编程方式获取eBay API的授权代码?

ngnix php8.0-fPM主要脚本未知

无法使用PHP DomDocument找到IMG元素

为什么注册SIGHUP的处理程序函数会阻止在PHP CLI中等待输入时点击X关闭Xterm窗口?""

如何优化-PHP 7.3.14+Laravel 6

WooCommerce产品按特定元数据的自定义数字排序选项

将产品类别添加到WooCommerce产品附加信息

将购买限制在WooCommerce中具有相同产品属性的项目

根据WooCommerce的定制订单状态增加产品库存

如果所有请求都通过index.php路由,如何使用htaccess文件强制使用HTTPS?

将自定义字段添加到管理产品 在 WooCommerce 3.2+ 中批量编辑

当未 Select 任何变体时,在 WooCommerce 可变产品上显示自定义文本

如何在 Laravel 迁移中使用日期时间和天数?

使用用户元数据填写 woocommerce checkout 字段

在WooCommerce单产品页面中显示特价产品的节省金额

ACF 更新字段功能不更新 WordPress 中的任何数据

保留 .htaccess 中的符号登录 URL

为什么 AJAX 请求没有通过 is_ajax_request() codeigniter 的条件?

遇到特定键时修改二维数组以创建嵌套数据集

即使密码匹配,密码处理程序也会返回错误