Char
Char

Reputation: 318

Display number of duplicates from database [SQL]

This is my code.

$sqlcount = "SELECT count(*) AS C, Horse_ID FROM images WHERE Horse_ID = 24 GROUP BY Horse_ID HAVING COUNT(*) > 1 LIMIT 0, 30";

//echo $sqlcount;       

$resultcount = $conn->query($sqlcount); 

$rowcount = $result->fetch_assoc();

echo $rowcount['C'];

Why won't it echo the number 4, which is what shows when I test it in phpmyadmin? There are 4 duplicate values in that table hence the 4.

Upvotes: 2

Views: 56

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

If you want the number of duplicates in the database, why not write the query to get that value?

SELECT COUNT(*)
FROM (SELECT count(*) AS C, Horse_ID
      FROM images
      WHERE Horse_ID = 24
      GROUP BY Horse_ID
      HAVING COUNT(*) > 1 
     ) i;

Then, you will only be returning one value from the database to the application (which is faster) and there is no need to artificially limit the count to 30.

Upvotes: 0

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

 $rowcount = $result->fetch_assoc();

to

 $rowcount = $resultcount->fetch_assoc();

Upvotes: 2

Related Questions