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

时间:2018-01-15 17:30:02

标签: php mysql codeigniter codeigniter-3 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”: enter image description here

NB:原谅我的英语: - )

3 个答案:

答案 0 :(得分:1)

更改模型中的功能:

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.

答案 1 :(得分:0)

使用有效记录:

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

中的视图调用模型方法也被认为是不好的做法

答案 2 :(得分:0)

您需要从查询中generate and return some "results"。另外,如图所示,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
}

我只是要求提供&#39; id&#39;领域。没有必要用&#39; *&#39;来要求所有人。查询应该更快,只需要一个。