如何使用自动加载codeigniter显示查询计数(*)中的数据?

pbgvytdp  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(345)

我在使用autoload时遇到了麻烦。例如:
我的模型:dataload.php

public static function footer(){
        $text = "Copyright © 2018 MyCompany";
        return($text);
    }

我的视图:view.php

<p class="xxx"><?php echo dataload::footer() ?></p>

有可能表现出来。但对于这个问题:

+------+------------+--------------+
| id   | name       | email_status |
+------+------------+--------------+
| 01   | Erick      | send         |
| 02   | Maya       | send         |
| 03   | Michael    | pending      |
+------+------------+--------------+

我的模型:dataload.php

public function emailsend(){
    return $this->db->query('SELECT COUNT(*) as total FROM user WHERE email_status = "send"');
}

我的观点:

<i class="ti ti-email"></i><span class="badge badge-primary"><?php echo dataload::emailsend() ?></span><span>Email</span>

那么,为什么数据不显示呢?
结果应显示“2”:

注:请原谅我的英语:-)

9udxz4iz

9udxz4iz1#

更改模型中的函数:

public function emailsend(){
    $q = $this->db->query('SELECT * FROM user WHERE email_status = "send"'); // you can select user_id here
    return $q->num_rows(); // this will return count    
}

然后在视图中使用上述函数。

NOTE: replace '*' with specific unique id. no need to select all the records.
b1payxdu

b1payxdu2#

您需要从查询中生成并返回一些“结果”。另外,如图所示, emailsend() 不定义为 static 所以这个电话 dataload::emailsend() 会失败的。

public static function emailsend(){
    //use method chaining instead of multiple lines with $this->db
    return $this->db
                ->query('SELECT COUNT(id) as total FROM user WHERE email_status = "send"')
                ->row() //the query results
                ->total; //the item of interest in results
}

我只是要“id”字段。没有必要用“*”来要求所有人。查询应该更快只要求一个。

hmmo2u0o

hmmo2u0o3#

使用活动记录:

public function get_count(){
    $this->db->select('*');
    $this-db->where('email_status', 'send');
    return $this->db->get('user')->count_all_results();
}

//usage

$count = $this->model->get_count();
var_dump($count); //outputs int of count

注意这个方法不是静态的,所以我们不使用 :: ,从中的视图调用模型方法也被认为是不好的做法 CI

相关问题