我是 Codeigniter 的新手,我需要在数据库中insert
数据后显示成功和错误消息。
如何在view
页面中显示消息?
这是我的编码:
模型
function addnewproducts($data)
{
if($data['product_name']!="" && $data['product_qty']!="" && $data['product_price']!="" && $data['date']!="")
{
$res=$this->db->insert('product_list',$data);
return $this->db->insert_id();
}
else
{
return false;
}
}
控制器
function addnewproduct()
{
$this->load->model('products');
$data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
$data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
$data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
$data['datetime']=date('d-m-Y');
$res = $this->products->addnewproducts($data);
if($res==true)
{
$data['success'] = 'Successful';
$this->load->view('addproduct',$data);
}
}
查看
<p><?php echo $success; ?></p>
答案 0 :(得分:2)
有很多方法,但我建议如下:
成功或错误时在控制器中设置临时会话:
$res = $this->products->addnewproducts($data);
if($res==true)
{
$this->session->set_flashdata('success', "SUCCESS_MESSAGE_HERE");
}else{
$this->session->set_flashdata('error', "ERROR_MESSAGE_HERE");
}
在视图中,您可以按如下方式显示flashdata:
echo $this->session->flashdata('success');
or
echo $this->session->flashdata('error');
来源:Codeigniter官方网站https://codeigniter.com/userguide3/libraries/sessions.html
答案 1 :(得分:0)
我很感谢你得到了答案,但我认为现在闪存数据有点老了,因为我们可以使用bootstrap来警告是否有任何错误并且在网页上看起来不错。
在控制器中
$res = $this->products->addnewproducts($data);
if($res==true)
{
$this->session->set_flashdata('true', 'write_the_message_you_want');
}
else
{
$this->session->set_flashdata('err', "write_the_message_you_want");
}
在视图中
<?php
if($this->session->flashdata('true')){
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata('true'); ?>
<?php
else if($this->session->flashdata('err')){
?>
<div class = "alert alert-success">
<?php echo $this->session->flashdata('err'); ?>
</div>
<?php } ?>
答案 2 :(得分:0)
控制器:
function addnewproduct()
{
$this->load->model('products');
$data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
$data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
$data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
$data['datetime']=date('d-m-Y');
if($this->products->addnewproducts($data));
{
$this->session->set_flashdata('Successfully','Product is Successfully Inserted');
}
else
{
$this->session->set_flashdata('Successfully','Failed To
inserted Product');
}
// redirect page were u want to show this massage.
redirect('Controller/Fucntion_name','refresh');
}// close function
观点: 在重定向页面上写下此代码顶部的表单
<?php if($responce = $this->session->flashdata('Successfully')): ?>
<div class="box-header">
<div class="col-lg-6">
<div class="alert alert-success"><?php echo $responce;?></div>
</div>
</div>
<?php endif;?>