1

I have this code:

$sql = "SELECT FOUND_ROWS() AS totalRows, COUNT(*) AS totalRefunds FROM table WHERE result = 'refunded'";
$totalRows = $conn->query( $sql )->fetch();
$totalRefunds = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0], "totalRefunds" => $totalRefunds[0] ) );

I want totalRows = 7 and totalRefunds = 1 but the above returns 0 for both. If I remove either the FOUND_ROWS() or COUNT(*) statements then the other one works. I'm guessing there's something wrong in SELECT but not sure what it is. Or maybe something else is wrong???

Thanks in advance.

aphextwig
  • 543
  • 2
  • 9
  • 23

3 Answers3

0

To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward

$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM  table WHERE result = 'refunded'";

and then SELECT FOUND_ROWS()

sshet
  • 1,152
  • 1
  • 6
  • 15
0

Try this way. Assuming you run the query with SQL_CALC_FOUND_ROWS prior to run this

SELECT (@variable := FOUND_ROWS()) AS totalRows, COUNT(*) AS totalRefunds 
FROM table WHERE result = 'refunded'
Akhil
  • 2,602
  • 23
  • 36
0

FOUND_ROWS() is used for counting rows as if LIMIT was ignored. It will not append total rows to other query result (unless you select them all, but there's no point if you only need count). Do it simple if you want this information only:

$sql = "SELECT COUNT(*) as totalRows FROM table";
$totalRows = $conn->query( $sql )->fetch();
$sql = "SELECT COUNT(*) as totalRefunds FROM table WHERE result = 'refunded'";
$totalRefunds = $conn->query( $sql )->fetch();

Other way (but different context) is to split counts into all 'result' column types (refunded/not refunded/other..) using GROUP BY so the the total rows can be obtained as sum of single counts returned.

shudder
  • 2,076
  • 2
  • 20
  • 21