我正在尝试找到一种方法从数据库中返回数据并计算我选择的行数。我尝试了一些我发现的东西,但它们或者最终出现错误,或者只是没有完全工作。
让我解释一下下面的代码。我正在从某个名为“posts”的表获取数据,其中图像表将连接到 posts 表。如果填写了 $category 参数以及 $start 和 $limit 参数,则会跳转 else 只选择特定类型的帖子。(type_bericht)。
function get($table, $category = null, $start = null, $limit = null, $conn) {
if (!$category) {
$query = $conn->query(
"SELECT $table.*, COUNT($table.id)
AS post_count, images.id AS imageid, images.url AS iurl
FROM $table
LEFT JOIN images ON images.id = $table.image_id
ORDER BY id DESC");
} else {
$query = $conn->query(
"SELECT $table.*, COUNT($table.id)
AS post_count, images.id AS imageid, images.url AS iurl
FROM $table
LEFT JOIN images ON images.id = $table.image_id
WHERE type_bericht = '$category'
ORDER BY id DESC LIMIT $start, $limit");
}
if ($query->rowCount() > 0) {
return $query;
} else {
return false;
}
}
这段代码没有显示任何错误,但它不能完全工作。它计算并返回(一个数字)从数据库中选择的帖子,但它只显示表中的一行。如果我删除“COUNT($table.id) AS post_count”部分,它会再次正常显示所有帖子,但我不希望这样。有人明白我可能会忘记什么或做得不对吗?
最佳答案
使用 SELECT SQL_CALC_FOUND_ROWS $table.* ...
(直接在每个 SELECT 之后添加“SQL_CALC_FOUND_ROWS”),然后使用 $db->query("SELECT FOUND_ROWS();")
获取计数。
关于php - 返回包含总行数的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25105732/