执行成功但num_rows返回0 [PHP-MySQL]

时间:2015-06-24 04:47:55

标签: php mysql mysqli

我刚才遇到的问题是,

$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();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:5)

  

是的,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”。

答案 1 :(得分:0)

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

$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();
            }
        }
    }
}