【问题标题】:Undefined variable error in view even after passing the data from controller即使从控制器传递数据后视图中的未定义变量错误
【发布时间】:2017-10-28 07:27:19
【问题描述】:

我正在尝试创建一个简单的计算器,它将通过单一方法执行计算

下面是我的控制器

类计算器扩展 CI_Controller {

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


    $this->load->helper('url');
}

    public function index()
    {
        $mid_cal = 0;
        $total_cost = 0;
        $this->load->view('Calculator',$total_cost,$mid_cal);
        //print_r($total_cost);

    }

    public function calculate()
    {
        //print_r($_POST);
        $qty_purchased = $this->input->post('qty_purchased');
        $item_cost = $this->input->post('item_cost');
        $mid_cal = $item_cost / $qty_purchased;
        $qty_used = $this->input->post('qty_used');
        $total_cost = $mid_cal * $qty_used ; 
        $this->load->view('Calculator',$total_cost,$mid_cal); 

        //$this->load->view('calculator');
    }


}

以下是我的看法

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<body>

<form action="<?php echo base_url(); ?>index.php/calculator/calculate" method='post'>
  Item:<br>
  <input type="text" name="item" >
  <br>
  Qty Purchased:<br>
  <input type="text" name="qty_purchased" >
  <br>
  Cost of Item:<br>
  <input type="text" name="item_cost" >
  <br>
  Mid Cal:<br>
  <input type="text" name="mid_cal" value="<?php echo $mid_cal ?>">
  <br>
  Qty Used:<br>
  <input type="text" name="qty_used" >
  <br>
  Total Cost:<br>
  <input type="text" name="total_cost" value="<?php echo $total_cost ?>">
  <br><br>
  <input type="submit" value="Submit">
</form> 



</body>
</html>

$total_cost 和 $mid_cal 的视图中出现未定义变量错误。我在计算函数中发送数据。我还尝试在我的索引函数中发送空白数据。我不知道如何解决这个问题。任何帮助都将受到欢迎。提前致谢。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    在您的控制器中。

    将索引方法/函数替换为以下并尝试。

    public function index()
    {
        $data['mid_cal'] = 0;
        $data['total_cost'] = 0;
        $this->load->view('calculator',$data);
        //print_r($total_cost);
    
    }
    

    您必须像上面一样将控制器中的数组传递给视图,现在您可以使用 $total_cost 和 $mid_cal 直接访问。

    【讨论】:

    • 非常感谢。它解决了我的问题。还有一件事我如何在视图表单中使用设置值功能。即使页面从 index() 函数加载到 calculate() 函数,我也希望我的所有数据都保留。我怎样才能做到这一点?
    • 也解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2021-10-14
    • 1970-01-01
    • 2017-09-03
    • 2018-08-23
    • 1970-01-01
    相关资源
    最近更新 更多