-1

I suppose that affected_rows returns the number of affected rows in the last query (for example an UPDATE) and num_rows the number of the rows in a result set (for example a SELECT).

What should I use in PDO?

PDOStatement::rowCount returns the number of rows affected in that statement but for most databases does not return the number of rows affected by a SELECT.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137

2 Answers2

0

equivalent of affected_rows: rowCount() http://php.net/manual/de/pdostatement.rowcount.php

If you want the number of rows of a select, perform a count().

Also as reference: PHP PDO - Num Rows

Twinfriends
  • 1,972
  • 1
  • 14
  • 34
  • I cannot perform a count(*) if the statement is already executed. I'm writing a wrapper for PDO and I need the function "numRows" passing a statement as input. – JustAnotherDeveloper Sep 27 '17 at 07:51
  • It is usefull if I have a "Storage" class that is a singleton and can store to a DB (so it will use PDO) but can store to file (so it will use files) and so on. User uses my class and call only "save/load" and I will use PDO/File/other depending on what I'm using. – JustAnotherDeveloper Sep 27 '17 at 09:21
  • I need it. Why are you telling that is useless if you don't know my project logics? – JustAnotherDeveloper Sep 27 '17 at 10:40
  • 1
    @TheDeveloper because I am an expert in PHP related superstitions and numRows is one of them. Every numRows() use case is either harmful or pointless, no exceptions. – Your Common Sense Sep 27 '17 at 12:01
  • @YourCommonSense I repeat: you don't know my project and its goal. :) – JustAnotherDeveloper Oct 01 '17 at 14:31
  • @TheDeveloper Well, of course, according to the Dunning-Kruger effect, you consider your goals unique and decisions ingenious. In reality, your project is the same as thousands others, and you just choose the wrong tool to achieve your goals and too arrogant to ask for the proper one. – Your Common Sense Oct 01 '17 at 14:41
  • 1
    @YourCommonSense. No. I consider my goals as they are: I have a particular request and I need to implement this function for backward-compatibility. This does not mean that I will use it. – JustAnotherDeveloper Oct 02 '17 at 21:45
0

It is mentioned in official documentation

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Number of matched rows can be forced by prepending SQL_CALC_FOUND_ROWS as stated in MySQL documentation for FOUND_ROWS

There already is related related answer by Paul Dixon explaining some details

rkosegi
  • 14,165
  • 5
  • 50
  • 83