如何使用 bind_result 与 get_result 的示例

2023-12-30

我想看一个如何使用调用的示例bind_result vs. get_result以及使用其中一种而不是另一种的目的是什么。

还有使用每种方法的优点和缺点。

使用这两种方法有什么限制,有什么区别吗?


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

示例 1 为$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>';
}

示例 2 为$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>';
}

绑定结果()

Pros:

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

Cons:

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

获取结果()

Pros:

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

Cons:

  • 需要 MySQL 本机驱动程序(mysqlnd http://php.net/manual/en/book.mysqlnd.php)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 bind_result 与 get_result 的示例 的相关文章

随机推荐