简体   繁体   中英

mysql_affected_rows returns 0

I have a problem with mysql_affected_rows() function in PHP. I use MySQL update, in phpMyAdmin I can see, that 'confirmed' changes from 0 to 1, but mysql_affected_rows still returns 0! I cannot find a solution. My code is:

$query = "UPDATE visits                 
SET confirmed = 1
WHERE id = ? AND confirmed = 0 AND expire >  now() - INTERVAL 10 MINUTE;";


$stmt = $this->conn->stmt_init();

if($stmt->prepare($query)) {
$stmt->bind_param('i',$id); //$id is a function parameter
$res = $stmt->execute();

$stmt->close();

echo mysql_affected_rows();
}

It seems you're using PDO, not the mysql_* functions. Therefore, you should uso PDOs rowCount function:

$query = "UPDATE visits                 
    SET confirmed = 1
    WHERE id = ? AND confirmed = 0 AND expire >  now() - INTERVAL 10 MINUTE;";

$stmt = $this->conn->stmt_init();

if($stmt->prepare($query)) {
    $stmt->bind_param('i',$id); //$id is a function parameter
    $res = $stmt->execute();

    echo $stmt->rowCount();

    $stmt->close();
}

Use affected_rows to get the number of affected rows when using an UPDATE statement :

$stmt = $this->conn->stmt_init();

if($stmt->prepare($query)) {
    $stmt->bind_param('i',$id); //$id is a function parameter
    $res = $stmt->execute();
    echo $stmt->affected_rows;
    $stmt->close();
}

It also needs to be before the close() statement

Use this http://www.php.net/manual/en/pdostatement.rowcount.php

The PDOStatement::rowCount return the number of rows affected by the query

You need to pass the connection as a parameter to the function.

echo mysql_affected_rows($this->conn);

http://php.net/manual/en/function.mysql-affected-rows.php

Since everyone seems to think you using PDO , whereas it looks more like MySQLi to me, here is the MySQLi way:

$query = "
  UPDATE visits                 
  SET confirmed = 1
  WHERE id = ?
    AND confirmed = 0
    AND expire > now() - INTERVAL 10 MINUTE
";

$stmt = $this->conn->stmt_init();

if ($stmt->prepare($query)) {
  $stmt->bind_param('i', $id); //$id is a function parameter
  $res = $stmt->execute();
  echo $stmt->affected_rows; // Here's the good stuff
  $stmt->close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM