【问题标题】:Execute Success but num_rows return 0 [PHP-MySQL] [duplicate]执行成功但 num_rows 返回 0 [PHP-MySQL] [重复]
【发布时间】:2015-06-24 04:47:54
【问题描述】:

我刚刚遇到的问题是,

$update_stmt->execute() 没问题,数据库中的数据已经更新

但是,$update_resultrow = $update_stmt->num_rows; 返回 0 ?

我尝试复制 MySQL 命令以在查询中运行,它也运行良好,如下所示:

UPDATE ACCOUNT_EMPLOYEE SET NAME = 'cccccc' WHERE ID = 1

问题代码在这里:

$update_sql = "UPDATE ACCOUNT_EMPLOYEE SET NAME = ? WHERE ID = ?";
if ($update_stmt = $conn -> prepare($update_sql)) {
    if ($update_stmt->bind_param("si",
        $newname,
        $acc_id
    )
    ) {
        if ($update_stmt->execute()) {
            // must declare here to be able to get num_rows
            $update_stmt->store_result();
            $update_resultrow = $update_stmt->num_rows;
            if ($update_resultrow == 0) {
                echo $error_forgot_noresult . '????' . $acc_id ;
                $update_stmt->close();
                $conn->close();
                exit();
            }
        }
    }
}

【问题讨论】:

  • $update_stmt->rowCount()替换$update_stmt->num_rows;
  • @Umair 那是 PDO,OP 正在使用 mysqli_
  • 所以应该是$update_stmt->num_rows();
  • $update_resultrow = $update_stmt->num_rows; 如果执行成功,你想在这里实现什么?如果是这样,您需要使用affected_rows,或阅读手册php.net/manual/en/mysqli-result.num-rows.php,即:从手册$rows = $query->num_rows; - 以及受影响的行php.net/manual/en/mysqli.affected-rows.php
  • 是的,Fred -ii-,我从未注意到它有 ->affected_rows。请作为答案发布,我会在这里标记它

标签: php mysql mysqli


【解决方案1】:

是的,Fred -ii-,我从未注意到它有 ->affected_rows。请作为答案发布,我会在这里标记它

根据 OP 的要求。

看到这里的目标是测试查询是否确实成功,需要使用affected_rows

按照手册http://php.net/manual/en/mysqli.affected-rows.php

printf("受影响的行(更新):%d\n", $mysqli->affected_rows);

  • 面向对象的风格

int $mysqli->affected_rows;


旁注:

使用

$update_resultrow = $update_stmt->num_rows;

并检查错误,会抛出错误,而不是“返回 0”。

【讨论】:

    【解决方案2】:

    尝试查找受查询影响的行数,而不是如下查找行数:

    $update_sql = "UPDATE ACCOUNT_EMPLOYEE SET NAME = ? WHERE ID = ?";
    if ($update_stmt = $conn -> prepare($update_sql)) {
        if ($update_stmt->bind_param("si",
            $newname,
            $acc_id
        )
        ) {
            if ($update_stmt->execute()) {
                // must declare here to be able to get num_rows
                $update_stmt->store_result();
                $update_resultrow = $update_stmt->affected_rows;
                if ($update_resultrow == 0) {
                    echo $error_forgot_noresult . '????' . $acc_id ;
                    $update_stmt->close();
                    $conn->close();
                    exit();
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-12
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多