Azevedo
Azevedo

Reputation: 2189

Cannot retrieve the number of affected rows of a PDOStatement

Using PDO connection to MySQL. I can't retrieve the number of affected rows for an "INSERT INTO" query

$sql = 'insert into ... ';
$q = $dbh->prepare($sql);
$q = $q->execute();
echo ( $q->rowCount() );
echo ( $q->affectedRows() );

Fatal error: Call to a member function rowCount() on a non-object.
Fatal error: Call to a member function affectedRows() on a non-object.

The record is inserted successfully but I can't check it because it won't return anything. What is wrong?

Upvotes: 1

Views: 68

Answers (1)

user142162
user142162

Reputation:

You should not be overwriting the $q variable when you call PDOStatement::execute(); it returns a boolean value. Simply remove the assignment when calling the execute method:

$q->execute();

There is also no method called affectedRows in PDOStatement. PDOStatement::rowCount() should be all that you need:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

Upvotes: 3

Related Questions