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)结果()

优点:

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

缺点:

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

获取结果()

优点:

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

缺点:

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

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

相关文章:

不同格式的php搜索日期

php - SQL数据库中的长字符串替代方案?

android - 为什么 Logcat 显示 "E/SQLiteLog﹕ (1) no such table: reg_info"?

mysql - 在 ruby​​ 中表示没有日期的时间

php - Docker-Compose 使用 PHP (MySQLi) 连接 MySQL 数据库

php - WordPress 中的 Mysqli 查询

php - cURL 不支持的 SSL 协议(protocol)

php - 在 PHP 中,我们如何返回一个大数组?

mysql - 如何在时间戳字段中搜索日期?

php - mysqli_fetch_assoc 只返回数组的第一个元素