mysqli_stmt_bind_result() 的参数计数错误

Wrong parameter count for mysqli_stmt_bind_result()

我的托管公司不提供 MySQLnd,所以我不得不更改我的代码。

这是我的代码:

<?php
include_once 'db.php';
$sql = "SELECT * FROM table1 ORDER BY id DESC";
$stmt = mysqli_stmt_init($connect);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "SQL statement failed";
} else{
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    while ($row = mysqli_fetch_assoc($result)) {
    ...

当我将 $result = mysqli_stmt_get_result($stmt); 更改为 $result = mysqli_stmt_bind_result($stmt); 时,它会给我

Warning: Wrong parameter count for mysqli_stmt_bind_result()

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given

这两天一直在搞这个,因为我是初学者,没能解决。我该怎么办?

请多多包涵,自从我使用程序 mysqli...

以来已经很久了

如果您希望动态绑定列参数并执行获取循环(因为 mysqlnd 不是一个选项),那么这里的代码可以实现。

mysqli_stmt_execute($stmt);

// now before you loop on $stmt->fetch, you must bind all the columns that exist
// to a row which will hold the values during the looping on fetch (yes, confusing)

$row    = array();  // will hold each fetch'd loop result
$params = array();  // something to pass keyed references to $row with
$params[] = $stmt;  // add the $stmt object as first param (for procedural way)

$meta = mysqli_stmt_result_metadata($stmt);// get what those columns will be

while($field = $meta->fetch_field()) {
    if (!isset($row[ $field->name ])) { $row[ $field->name ] = null; } // set if not set
    $params[] = &$row[ $field->name ]; // add reference to keyed row value
}

$meta->close();// metadata no longer needed, close it

call_user_func_array('mysqli_stmt_bind_result', $params);

while (mysqli_stmt_fetch($stmt)) {

    // in here you then have $row to use as before
    echo $row['id'];

}

现在,您可能认为我在这里矫枉过正了……是的。该示例用于处理 unknown sql 列抓取(使用 SELECT * 语法)。但是,如果您知道所有列都出来了,您可以像这样在 while 循环之前简单地绑定每一列:

mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $col2, $col3);

while (mysqli_stmt_fetch($stmt)) {

    // in here you then use $id, $col2, $col3
    echo $id;

}

这就是为什么切换到 PDO 库可以让事情变得非常简单,因为它提供了在一个简单的循环中简单地获取具有关联键名的行的规定,就像您知道并喜欢 mysqlnd可用的。但是,如果 PDO 也不是一个选项,那么您将不得不采用痛苦而神秘的方式来处理“绑定”和“我的sqli”。