Execute Success but num_rows return 0 [PHP-MySQL]

浪尽此生 提交于 2020-01-03 21:03:42

问题


The problem I just got is,

the $update_stmt->execute() is ok, and data in database already update

but, $update_resultrow = $update_stmt->num_rows; return 0 ?

I tried to copy MySQL command to run in query and it also worked well, like this:

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

Problem's Code here:

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

回答1:


Yes, Fred -ii-, I never noticed that it has ->affected_rows. please post as answer, and I will marked it here

As per OP's request.

Seeing that the goal here is to test if the query was indeed successful, you need to use affected_rows.

As per the manual http://php.net/manual/en/mysqli.affected-rows.php

printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

  • Object oriented style

int $mysqli->affected_rows;


Sidenote:

Using

$update_resultrow = $update_stmt->num_rows;

and checking for errors, would have thrown an error, rather than "return 0".

  • http://php.net/manual/en/mysqli.error.php



回答2:


Try to find the number of rows affected by your query instead of finding number of rows as below:

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


来源:https://stackoverflow.com/questions/31017831/execute-success-but-num-rows-return-0-php-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!