Php - passing a variable from controller to view

断了今生、忘了曾经 提交于 2019-12-24 12:05:15

问题


whenever I run this code i get the error of undefined variable $d, so i noticed i have to pass the variable from the controller to the view. I am new to MVC, hence why i would be grateful if someone helps me with this issue.

This is my implementation so far: **

Controller

**

class ControllerModuleGetstoreproducts extends Controller{
    public function index() {
        $object = new ModelGetstoreproducts();
        $d = $object->fetch();
        require_once "getstoreproducts.php";
    }
    function returndata(){
        $this->db->select("count(*)");
        $this->db->from("oc_product");
        $query = $this->db->get();
        return $query->result();
    }
}

Model

<?php
class ModelGetstoreproducts{
    function fetch(){
        $sql = 'SELECT count(*) FROM oc_product';
        $req = @mysql_query($sql);
        return @mysql_fetch_object($req);
        //return $req;

    }
}
?>

View

<p>The total is <?php var_dump($d) ?></p>

回答1:


Try this update to your files:

Controller:

    class ControllerModuleGetstoreproducts extends Controller{

    public $data;

    public function index() {
        $object = new ModelGetstoreproducts();
        $this->data['products'] = $object->fetch();
        require_once "getstoreproducts.php";
    }
    function returndata(){
        $this->db->select("count(*)");
        $this->db->from("oc_product");
        $query = $this->db->get();
        return $query->result();
    }
}

View:

<p>The total is <?php var_dump($this->data['products']) ?></p>



回答2:


Pass your id from View to Controller and get it into Model.Apply this rule You will not get any kind of error.



来源:https://stackoverflow.com/questions/35428199/php-passing-a-variable-from-controller-to-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!