88

我想看一个例子,说明如何调用 using bind_resultvs.get_result以及使用其中一个的目的是什么。

还有使用每个的利弊。

使用其中任何一种的限制是什么,是否有区别。

4

4 回答 4

209

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

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

绑定结果()

优点:

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

缺点:

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

获取结果()

优点:

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

缺点:

  • 需要 MySQL 本机驱动程序 ( mysqlnd )
于 2013-09-12T00:02:14.930 回答
3

您可以在相应的手册页上找到示例,get_result()并且bind_result().

虽然利弊很简单:

  • get_result()是处理结果的唯一明智的方法
  • 但它可能并不总是在某些过时且不受支持的 PHP 版本上可用

在现代 Web 应用程序中,数据永远不会在查询后立即显示。必须首先收集数据,然后才能开始输出。或者即使您不遵循最佳实践,也存在必须返回数据而不是立即打印的情况。

牢记这一点,让我们看看如何编写代码,使用这两种方法将所选数据作为关联数组的嵌套数组返回。

bind_result()

$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query1);
$stmt->bind_param('s',$id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $first_name, $last_name, $username);
$rows = [];
while ($stmt->fetch()) {
    $rows[] = [
        'id' => $id,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'username' => $username,
    ];
}

并记住每次在表中添加或删除列时编辑此代码。

get_result()

$query2 = 'SELECT * FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query2);
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

当表结构改变时,这段代码保持不变。

还有更多。
如果您决定将准备/绑定/执行的无聊例程自动化为一个整洁的函数,该函数将像这样调用

$query = 'SELECT * FROM `table` WHERE id = ?';
$rows = prepared_select($query, [$id])->fetch_all(MYSQLI_ASSOC);

这将get_result()是一项相当合理的任务,只需几行代码。但这bind_param()将是一个乏味的探索。

这就是为什么我称该bind_result()方法为“丑陋”的原因。

于 2013-09-12T06:46:59.317 回答
2

get_result()仅通过安装 MySQL 本机驱动程序 (mysqlnd) 在 PHP 中可用。在某些环境中,可能无法或不希望安装 mysqlnd。

尽管如此,您仍然可以使用 mysqli 进行SELECT *查询,并使用字段名称获取结果 - 尽管它比 using 稍微复杂一些get_result(),并且涉及使用 PHP 的call_user_func_array()函数。请参阅如何在 php 中使用 bind_result() 而不是 get_result() 中的示例,该示例执行简单的SELECT *查询并将结果(带有列名)输出到 HTML 表。

于 2016-07-20T21:26:48.337 回答
0

我注意到的主要区别是,当您尝试在其他 $stmt 中编写嵌套的 $stmt代码bind_result(),这会给您带来错误(没有):2014mysqli::store_result()

准备失败:(2014)命令不同步;你现在不能运行这个命令

例子:

  • 主代码中使用的函数。

    function GetUserName($id)
    {
        global $conn;
    
        $sql = "SELECT name FROM users WHERE id = ?";
    
        if ($stmt = $conn->prepare($sql)) {
    
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->bind_result($name);
    
            while ($stmt->fetch()) {
                return $name;
            }
            $stmt->close();
        } else {
            echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
        }
    }
    
  • 主要代码。

    $sql = "SELECT from_id, to_id, content 
            FROM `direct_message` 
            WHERE `to_id` = ?";
    if ($stmt = $conn->prepare($sql)) {
    
        $stmt->bind_param('i', $myID);
    
        /* execute statement */
        $stmt->execute();
    
        /* bind result variables */
        $stmt->bind_result($from, $to, $text);
    
        /* fetch values */
        while ($stmt->fetch()) {
            echo "<li>";
                echo "<p>Message from: ".GetUserName($from)."</p>";
                echo "<p>Message content: ".$text."</p>";
            echo "</li>";
        }
    
        /* close statement */
        $stmt->close();
    } else {
        echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
    }
    
于 2015-11-03T22:32:01.813 回答