且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sql直接获取表中的行数的方法

更新时间:2023-02-03 15:01:04

这将告诉您行数:

 从库
$ p中选择COUNT(*) $ p>

Hi again people of ***. 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.

This will tell you the number of rows:

SELECT COUNT(*) FROM gallery