gpt4 book ai didi

php - 如何使用 bind_result 与 get_result 的示例

转载 作者:行者123 更新时间:2023-11-30 22:42:11 25 4
gpt4 key购买 nike

我想看一个示例,说明如何使用 bind_resultget_result 进行调用,以及使用其中一个的目的是什么。

还有各自的优缺点。

使用这两者的限制是什么,有区别吗。

最佳答案

虽然这两种方法都适用于 * 查询,但是当使用 bind_result() 时,列通常在查询中明确列出,因此可以在分配时引用列表bind_result() 中的返回值,因为变量的顺序必须严格匹配返回行的结构。

$query1 的示例 1 使用 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>';
}

$query2 的示例 2 使用 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)结果()

优点:

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

缺点:

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

获取结果()

优点:

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

缺点:

  • 需要 MySQL native 驱动程序 ( mysqlnd )

关于php - 如何使用 bind_result 与 get_result 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30815774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com