为了账号安全,请及时绑定邮箱和手机立即绑定

mysqli_stmt_bind_result() 的参数计数错误

mysqli_stmt_bind_result() 的参数计数错误

PHP
富国沪深 2023-09-08 10:22:44
我的托管公司不提供 MySQLnd,所以我必须更改代码中的一些内容。这是我的代码:<?phpinclude_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我已经为此工作了两天,但由于我是初学者,所以无法解决。我应该怎么办?
查看完整描述

1 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

请耐心听我说,因为自从我使用程序 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'];


}

现在,你可能会认为我在这里太过分了……是的。该示例用于处理未知的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这也不是一个选项,那么您将面临痛苦且神秘的方法来处理“binds”和“mysqli”。


查看完整回答
反对 回复 2023-09-08
  • 1 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信