gpt4 book ai didi

php - 我们可以在分页中使用 count(*) 而不是使用 count 来获取表中的记录数吗?

转载 作者:行者123 更新时间:2023-11-29 06:28:06 24 4
gpt4 key购买 nike

下面是代码,这里我使用了“select count(*) from departments”而不是“select * from departments”,所以这段代码哪里错了。谁能帮我解决一下..

$num_rec_per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * $num_rec_per_page;
$sql_query = "SELECT * FROM departments LIMIT $start_from, $num_rec_per_page";
$result = $db_connection->query($sql_query);
if($result->num_rows > 0){
while($rows = $result->fetch_assoc()){
echo "<tr>";
echo "<td>".$rows["id"]."<td>";
echo "<td>".$rows["name"]."<td>";
echo "<tr>";
}
}
$sql = "SELECT count(*) FROM departments"; //select query for total records
$rs_result = $db_connection->query($sql); //run the query
$total_records =$rs_result->num_rows; //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);

echo "<a href='index.php?page=1'>".'|<'."</a> "; // Goto 1st page

for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='index.php?page=$total_pages'>".'>|'."</a> ";

最佳答案

我认为您唯一的问题是您尝试获取记录总数的方式。设置 SQL 查询以进行计数,然后通过读取返回的唯一行来检索它:

$sql = "SELECT count(*) AS total_records FROM departments";
$rs_result = $db_connection->query($sql);
$total_records = $rs_result->fetch_assoc()['total_records'];

关于php - 我们可以在分页中使用 count(*) 而不是使用 count 来获取表中的记录数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com