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/30815774/

相关文章:

php - 我想显示相同的 ID 数据

php - 当编写此代码时出现 localhost 重定向并且此页面无法正常工作?

php - 使用这个自定义的 MySQLi 转义 PHP 函数有什么问题吗?

php - 使用ajax将数组发布到cakePHP中的 Controller

php - MYSQL 日期范围查询奇怪的行为

php - SQL 编码问题 (Â)

php - Mysql错误-第1行接近'1'

php - 使用不同类型的用户在mySQL上创建角色

php - 查询codeigniter仅在mysql DB中插入1位数据类型

php - 使用 UNION 查询在 while 语句中获取总数