为foreach()提供的未定义变量和无效参数

时间:2016-10-09 07:14:29

标签: php html codeigniter

我试图学习codeigniter,我在这里遇到问题。在视图上为foreach()提供了未定义的变量和无效参数。这是代码:

Model(Model_Users.php):

class Model_users extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function getFirstNames(){
        $query = $this->db->query('SELECT firstname FROM users');

        if($query->num_rows() > 0) {
            return $query->result();
        } else {
            return NULL;
        }
    }

    function getUsers(){

        $query = $this->db->query('SELECT * FROM users');

        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return NULL;
        }
    }
}

Controller(welcome.php):

class Welcome extends CI_Controller {

    public function index()
    {
        $this->home();
    }

    public function home()
    {
        $this->load->model('model_users');

        $data['title'] = 'MVC Cool Title';
        $data['page_header']='Intro to MVC Design';
        $data['firstnames'] = $this->model_users->getFirstNames();

        $data['users'] = $this->model_users->getUsers();

        $this->load->view('welcome_message',$data);
    }
}

查看(Welcome_message.php):

<div id="container">
    <h1><?php echo $page_header ?></h1>

    <div id="body">
        <?php
            foreach ($firstnames as $object) {
                echo $object->firstname .'<br/>';
            }
            echo '<br/><hr/><br/>';

            foreach ($users as $object){
                echo $object->firstname . '\'s email address is'. $object->email . '<br/>';
            }
        ?>
    </div>

    <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>

请帮我解决我的代码有什么问题?

3 个答案:

答案 0 :(得分:0)

首先检查值是否返回任何值或不在控制器中写入此代码 使用

def processNote(note): if note == 'C': return 262 ... ; 和 var_dump($firstnames);

我认为没有数据从模型返回 检查表中的任何数据 感谢

答案 1 :(得分:0)

You can eliminate the error by using return []; instead of return null; instead of checking for that case in every foreach call, because it appears that your user table might be empty based on the code provided.

答案 2 :(得分:0)

修改您的模型功能,如下所示

function getFirstNames(){
    $query = $this->db->get('users')->row()->firstname;

    if($query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return NULL;
    }
}

function getUsers(){


    $query = $this->db->get('users');
    if ($query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return NULL;
    }
}

希望这会有所帮助