Search code examples
sqlmysqlsqlitepostgresqlrowcount

sql direct way to get number of rows in table


Hi again people of stackoverflow. I have a routine that has a step that I find unnecessary lets say you want to get all the images from a gallery, and limit a certain number of images per page.

$db = PDO object
$start = (pagenum x images per page)
$limit = (images per page)
$itemsdata = $db->query("SELECT id,name FROM gallery LIMIT $start,$limit")->fetchAll();
$numitems = $db->query("SELECT id FROM gallery")->rowCount();

$imgsdata is a array of all the images in a gallery for example. $numimgs is the number of images that the gallery has.

you would need $imgsdata to do a foreach loop on each image in the array, while $numimgs is needed to generate the page numbering (e.g. << 1 2 3 4 >>)

my grudge is with $db->query("SELECT id FROM gallery")->rowCount(); It feels completely like some sort of cheat, isn't there a direct way to get the number of rows in a table, something like SELECT gallery.Rows?

p.s. currently I'm using SQLite, but I'd need it for MySQL and PostgreSQL as well.


Solution

  • This will tell you the number of rows:

    SELECT COUNT(*) FROM gallery