为什么我在视图中的显示控制器数组中得到错误未定义变量?

时间:2015-10-02 04:50:52

标签: php codeigniter

我的控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyAppointment extends CI_Controller {

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


        $this->load->model('appointment_model','',TRUE);

    }

    function index()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('rdatetimepicker', 'Appointment date', 'trim|required|xss_clean');

        if($this->form_validation->run() == FALSE)
        {
            $this->load->view("pages/appointment");
        }
        else
        {
            $this->appointment_model->insert();
            $data['posts'] = "hih";

            $this->load->view('pages/appointment',$data);
        }

    }

}

我的观点:

<?php

    echo $posts;
?>

1 个答案:

答案 0 :(得分:2)

您收到错误,因为在验证条件为 false 时,视图不会显示$posts,因为您在开始时或在每个if条件中根据您的编码样式初始化$data['posts']=""; < / p>

 function index()
        {
            $this->load->library('form_validation');

        $this->form_validation->set_rules('rdatetimepicker', 'Appointment date', 'trim|required|xss_clean');

        if($this->form_validation->run() == FALSE)
        {
           $data['posts']="";  //declare posts here              
          $this->load->view('pages/appointment',$data);

        }
        else
        {
            $this->appointment_model->insert();
            $data['posts'] = "hih";

            $this->load->view('pages/appointment',$data);
        }

    }

或者您可以在视图之前检查数组,就像这样;如果你不想改变你的控制器

<?php
    if(isset($posts))
    echo $posts;
?>