【问题标题】:How to show data from query count(*) with autoload Codeigniter?如何使用自动加载 Codeigniter 显示来自查询计数(*)的数据?
【发布时间】:2018-01-15 17:30:01
【问题描述】:

我在使用自动加载时遇到了麻烦。 例如:

我的模型: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”:

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

【问题讨论】:

    标签: php mysql codeigniter codeigniter-3 autoload


    【解决方案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.
    

    【讨论】:

    • 如果这对您有用,请接受,以便其他用户可以获取。
    【解决方案2】:

    使用活动记录:

    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中的视图调用模型方法也被认为是不好的做法

    【讨论】:

    • 我同意从视图调用模型会破坏 MVC 模式。但是由于调用是静态的(我假设缺少的限定符是错字),它与使用传递给视图的 var 或使用常量并没有什么不同。有很多人会反对在 OO PHP 中使用静态,而 IMO 是更大的问题。
    【解决方案3】:

    您需要从查询中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
    }
    

    我只是在询问“id”字段。用“*”要求所有都没有意义。查询应该更快,只要求一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多