Martin Blore
Martin Blore

Reputation: 2195

MySql affected_rows always 0 but UPDATE works

The following code in question always logs that the affected_rows was 0. I check my DB, the row updates fine everytime. Why is it 0?

public static function updateNextRunTime($nextRunTime)
    {
        $mysqli = new mysqli(GDB_HOST, GDB_USERNAME, GDB_PASSWORD, GDB_NAME);

        if ($mysqli->connect_errno)
        {
            throw new Exception('DB Connection Failed. Error Code: ' . $mysqli->connect_errno);
        }

        $cmd = $mysqli->prepare("UPDATE balanceagent SET NextRunTime = ? WHERE Id = 1");
        if (!$cmd)
        {
            throw new Exception($mysqli->error);
        }

        $cmd->bind_param('s', $nextRunTime);
        $cmd->execute();

        $rows = $mysqli->affected_rows;

        $cmd->close();
        $mysqli->close();

        if ($rows != 1)
        {
            logToFile("Balance Agent Error - Failed to update the next run time! - Affected rows: " . $rows);
        }
    }

Upvotes: 0

Views: 118

Answers (2)

user1864610
user1864610

Reputation:

For prepared statements you should be using the mysqli_stmt::affected_rows form :

$cmd->bind_param('s', $nextRunTime);
$cmd->execute();

$rows = $cmd->affected_rows;

Upvotes: 1

DanielX2010
DanielX2010

Reputation: 1908

Your should check $cmd->affected_rows; instead of $mysqli->affected_rows;

Upvotes: 1

Related Questions