我正在尝试计算MySQL数据库中显示给用户的活动结果数 但我只计算行数,但我似乎无法计算有多少活动/非活动/已删除
<?php
$user_id = $this->session->userdata('user_id');
$query = $this->custom_query("SELECT post_status FROM listings WHERE user_id=$user_id ");
if($query->num_rows()>0){
foreach($query->result() as $row){
if($row->post_status == 'active'){
echo $row->num_rows();
}
}
}
?>
答案 0 :(得分:1)
你可以使用sql count函数,在这里查看有效的函数https://www.w3schools.com/sql/sql_count_avg_sum.asp
回答;
select count(id) as active_count from listings WHERE user_id=$user_id and post_status = 'active'
答案 1 :(得分:1)
您可以使用修改后的sql语句尝试此修改后的代码。
一个查询中有多个计数。
<?php
$user_id = $this->session->userdata('user_id');
$query = $this->custom_query("SELECT
COUNT(CASE WHEN post_status = 'active' THEN 1 END) as active_total,
COUNT(CASE WHEN post_status = 'inactive' THEN 1 END) as inactive_total,
COUNT(CASE WHEN post_status = 'deleted' THEN 1 END) as deleted_total
FROM listings WHERE user_id = $user_id");
$row = $query->result();
echo "Active: ".$row[0]->active_total."<br/>\n";
echo "Inactive: ".$row[0]->inactive_total."<br/>\n";
echo "Deleted: ".$row[0]->deleted_total."<br/>\n";
?>
答案 2 :(得分:0)
计算检索到的数据库记录的简便方法是在查询中使用num_rows
$user_id = $this->session->userdata('user_id');
return $this->db->get_where('listings', array('user_id'=> $user_id, 'post_status' => 'active'))->num_rows();