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

标签 php mysql mysqli prepared-statement

我想看一个示例,说明如何使用 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_result()

优点:

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

缺点:

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

get_result()

优点:

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

缺点:

  • 需要 MySQL 原生驱动程序 (mysqlnd)

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

相关文章:

php - Wordpress:如果(网址为 example.com/sitemap)执行此操作...

php - 当我使用 php 包含 WHERE 时,从 sql 中读取停止

php - 关于 MySQL JOIN 的建议

php - 选择查询中的MySQL计算差异

c# - 添加 ADO.NET 实体模型崩溃

mysql - 通过其他表将一个表连接到另一个表

php - Mysql日期错误

MYSQL查询: Remove duplicates from query while adding counts

php - php 文档中未选择数据库

php - Mysql fetch() 返回 FALSE