1

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?

1
  • @BillKarwin Ah you're right. Commented Mar 20, 2014 at 20:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! $dbh I meant. rowCount() worked. But not affectedRows(). When should I use affectedRows() then?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.