I have been having a problem... a frustrating problem at that. I cannot seem to edit a specific row in Codeigniter. I have found previous questions on the same here, and even tried the solutions but to no avail. I am press for time on this project I am undertaking. Before you regard this question as a duplicate please have a look see. Any help will be greatly appreciated... Thank you in advance My code snippets are below:
Codeigniter/Controller
<?php..
//Selects all from admin table
function get_admin(){
$data['query'] = $this->Superuser_Model->selectadmin();
}
//brings in the view
// function editAdmin(){
// $data['content'] = 'admin/edit_admin';
// $this->load->view('include/template_back', $data);
// }
//click a specific row in the view (tabulated data)
function edit($id){
$data['array']= $this->Superuser_Model->editadmin($id);
// $data['content'] = 'admin/edit_admin';
$this->load->view('include/header_back');
$this->load->view('admin/edit_admin', $data);
$this->load->view('include/footer_back');
}
//Should update the from
function update_superuser(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()==FALSE)
{
$data['content'] = 'admin/add_admin';
$this->load->view('include/template_back', $data);
}
else
{
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$date_added = $this->input->post('date_added');
$this->Superuser_Model->update_superuser($username,$password,$date_added);
redirect('login/index', 'refresh');
}
}
..?>
Codeigniter/Model
<?php...
function selectadmin(){
// $id = $this->uri->segment(3);
$query = $this->db->get('admin');
return $query->result_array();
}
function editadmin($id){
$id = $this->uri->segment(3);
$query = $this->db->get('admin');
$this->db->where('adminID', $id);
return $query->result_array();
}
function update_superuser($data, $id){
$this->uri->segment(3);
$id = $this->input->post('adminID');
$data = array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password'),
'date_added'=> $this->input->post('date_added')
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
...?>
Codeigniter/View
...
<?php echo form_open('superuser/update_superuser', array('class' => 'form-horizontal', 'enctype' => 'multipart/form-data')); ?>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-btns">
×
−
</div>
<h4 class="panel-title">Admin Details</h4>
<p>Please, Insert your details here below... (for Superuser use only)</p>
</div>
<div class="panel-body panel-body-nopadding">
<!--username-->
<div class="form-group">
<!-- <input type="hidden" name="adminID" class="form-control" value="<?php echo $array->adminID;?>"/> -->
<label class="col-sm-4 control-label">Username</label>
<div class="col-sm-8">
<input type="text" name="username" class="form-control" value="<?php echo $array['username'];?>"/>
</div>
// <?php // form_error('username');?>
</div>
<!--password-->
<div class="form-group">
<label class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" name="password" class="form-control" value="<?php echo $array['password'];?>"/>
</div>
<?php //echo form_error('date_added');?>
</div>
<!--Date Added-->
<div class="form-group">
<label class="col-sm-4 control-label">Date</label>
<div class="col-sm-8">
<input type="text" name="date_added" class="form-control" id="datepicker" value="<?php echo $array['date_added'];?>" /> <img src="<?php echo base_url();?>components/backend/images/calendar.gif" alt="" /><br /><br />
</div>
<?php //echo form_error('date_added');?>
</div>
</div><!-- panel-body -->
<div class="panel-footer">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div><!-- panel-footer -->
</div><!-- panel-default -->
<?php form_close();?>
...</body></html>
Errors Displayed
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: admin/edit_admin.php
Line Number: 54
A PHP Error was encountered
Severity: Notice
Message: Undefined index: password
Filename: admin/edit_admin.php
Line Number: 62
A PHP Error was encountered
Severity: Notice
Message: Undefined index: date_added
Filename: admin/edit_admin.php
Line Number: 70
Seems like not correct $array['username'], $array['password'] and $array['date_added']. Print out $array first and you'll see what's wrong.
I see a few things... Firstly, you are trying to use the $this->input->post method which is beyond the scope of the model (relevant only to the controller). This is what provides you with the php errors...
Secondly, you are passing the right parameters to the model (minus cleaning them from XSS attacks, notice), but you are accepting different ones, so in the model your function should look something like this
function update_superuser($username, $password, $data_added){
$id = $this->input->post('adminID'); // I believe you should be getting the id from the database/session honestly, much safer in these cases
$data = array(
'username'=> $username,
'password'=> $password,
'date_added'=> $data_added
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
Hope this helps!
You are passing 3 parameters to your update_superuser() function here
$this->Superuser_Model->update_superuser($username,$password,$date_added);
and your function in your model only takes 2 params:
function update_superuser($data, $id){
$this->uri->segment(3);
$id = $this->input->post('adminID');
$data = array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password'),
'date_added'=> $this->input->post('date_added')
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
Related
I am making a news editing feature using CodeIgniter 3, there is also an image edit here
But has errors like the following,
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Operator::edit_berita(), 0 passed in D:\xampp\htdocs\ui-desa\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Filename: D:\xampp\htdocs\ui-desa\application\controllers\Operator.php
Line Number: 164
Backtrace:
File: D:\xampp\htdocs\ui-desa\index.php
Line: 315
Function: require_once
Controller Operator.php
public function edit_berita($id_berita)
{
$data['title'] = 'Edit Berita';
$data['user'] = $this->db->get_where(
'user',
['id' => $this->session->userdata('id')],
['email' => $this->session->userdata('email')]
)->row_array();
$data['berita'] = $this->model_berita->getAllBeritaById($id_berita);
// $data['berita'] = $this->db->get('berita')->result_array();
// $data['berita'] = $this->model_berita->getNama();
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('isi_berita', 'Isi Berita', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('operator/editberita', $data);
$this->load->view('templates/footer');
} else {
$judul_berita = $this->input->post('judul_berita');
$slug_berita = url_title($this->input->post('judul_berita'), 'dash', 'TRUE');
$isi_berita = $this->input->post('isi_berita');
$tgl_berita = date('Y-m-d H:i:s');
$id = $this->session->userdata('id');
// Cek Jika Ada Gambar Yang DiUpload
$upload_image = $_FILES['gambar_berita'];
if ($upload_image) {
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['upload_path'] = './gambar_berita/';
$this->load->library('upload', $config);
if ($this->upload->do_upload('gambar_berita')) {
$old_image = $data['berita']['gambar_berita'];
if ($old_image != 'default.jpg') {
unlink(FCPATH . 'gambar_berita/' . $old_image);
}
$new_image = $this->upload->data('file_name');
$this->db->set('gambar_berita', $new_image);
} else {
echo $this->upload->display_errors();
}
}
$this->db->set('id_berita', $id_berita);
$data = array(
'judul_berita' => $judul_berita,
'isi_berita' => $isi_berita
);
$this->db->where($data);
$this->db->update('berita');
$this->session->set_flashdata('message', '<div class="alert alert-success" role ="alert"> Berita Berhasil di Reposting </div>');
redirect('operator/berita');
}
}
Model model_berita.php
public function getAllBeritaById($id_berita)
{
return $this->db->get_where('berita', ['id_berita' => $id_berita])->row_array();
}
View edit_berita.php
<!-- CK Editor 4 -->
<script src="<?= base_url('ckeditor/'); ?>ckeditor.js"></script>
<script src="<?= base_url('ckeditor/'); ?>samples/js/sample.js"></script>
<link href="<?= base_url('ckeditor/'); ?>samples/css/samples.css" rel="stylesheet">
<link href="<?= base_url('ckeditor/'); ?>samples/toolbarconfigurator/lib/codemirror/neo.css" rel="stylesheet">
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">
<?= $title; ?></h1>
<div class="row">
<div class="col-lg">
<?php if (validation_errors()) : ?>
<div class="alert alert-danger" role="alert">
<?= validation_errors(); ?>
</div>
<?php endif; ?>
<?= $this->session->flashdata('message'); ?>
<?= form_open_multipart('operator/edit_berita') ?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $berita['id_berita']; ?>">
<div class="modal-body">
<div class="form-group">
<small>Masukkan Judul Berita</small>
<input type="text" value="<?= $berita['judul_berita']; ?>" class="form-control" id="judul_berita" name="judul_berita" placeholder="Judul Berita..." required>
</div>
<div class="form-group">
<small>Masukkan Isi Berita</small>
<textarea class="form-control" name="isi_berita" id="editor" required><?= $berita['isi_berita']; ?></textarea>
</div>
<div class="form-group">
<label for="gambar_berita">Ganti Gambar Berita</label>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-3">
<img src="<?= base_url('gambar_berita/') . $berita['gambar_berita']; ?>" class="img-thumbnail" alt="Gambar Berita">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="gambar_berita" name="gambar_berita">
<label class="custom-file-label" for="gambar_berita">Choose File</label>
</div>
</div>
</div>
</div>
<br>
<button type="reset" class="btn btn-danger" data-dismiss="modal">Reset</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<script>
initSample();
</script>
I've tried a number of ways, but it's still an error too. Please help so that my news update feature can work. Thanks.
Well your error clearly states that your method.
public function edit_berita($id_berita)
is expecting a parameter, which you have named $id_berita.
I cannot tell why you decided to have a parameter in this method, so I can only make some suggestions to help you solve your issue.
From what I can gather from your supplied code you could try the following options...
Option 1:
From what I can tell from your form, you are posting this as a hidden input, so you should be retrieving it from the Post Data.
<input type="hidden" name="id" value="<?= $berita['id_berita']; ?>">
So your method should become...
public function edit_berita()
{
$id_berita = $this->input->post('id'); // This needs to be validated
// The rest of your code below here...
}
But I would be validating that value to see if it exists before processing anything else.
Personally, I would be naming it as id_berita in your form to keep things matched up to avoid mistakes.
Option 2:
Another option would be to modify your form_open_mulitpart from
<?= form_open_multipart('operator/edit_berita') ?>
To include the id to pass in as a parameter
<?= form_open_multipart('operator/edit_berita/'.$berita['id_berita']) ?>
You will have to check that by inspecting your HTML Source using your Browsers "View Source" and inspect the HTML to see that it has ended up in the right place.
That will let you use your existing method
public function edit_berita($id_berita)
But again, you would need to validate that the passed in $id_berita is correct.
Which ever way you go, is your choice. You just need to read through your code and understand it a bit better.
I hope that gives you some guidance.
I am not very much sure if my title question is correct, however i am facing sever error of multiple loops within foreach, despite of having only one item in array. I am pasting my code here;
Display (Controller)
$table_data = array(
'table_data' => $this->display_model->get_table_data($table_name),
'edit_table_data'=>$this->display_model->get_table_data($table_name,$row_id)
);
$form_name='edit_'.$table_name;
$this->load->view('header');
$this->load->view($form_name,$table_data);
$this->load->view('footer');
You can see tabe_data and edit_table_data is calling same function with different parameter.
Here i doubt on the time scheduling between these two function calls (which honestly i am wrong because codeigniter manages function calls)
Display_model (Model)
public function get_table_data($table_name,$row_id=null)
{
$return = "";
if ($row_id != null)
{
switch ($table_name) {
case 'user':
//$return = $this->db->where($table_name."_id",$row_id)->get($table_name)->result();
$return = $this->db->select($table_name.'.*,country.country_name')
->join('country','country.country_id=user.user_country_id','left')
->where($table_name.'_id',$row_id)
->get($table_name)->result();
break;
case 'user_document':
//$return = $this->db->where($table_name."_id",$row_id)->get($table_name)->result();
$return = $this->db->select($table_name.'.*,document.document_name')
->join('document','document.document_id=use_document.document_id','left')
->where($table_name.'_id',$row_id)
->get($table_name)->result();
break;
default:
$return = $this->db->where($table_name."_id",$row_id)->get($table_name)->result();
break;
}
if($return != null)
{
return $return;
}
else
{
return "no_data";
}
}
Here is my view where i am getting error
<?php foreach ($edit_table_data as $etd_row) {?>
<form method="post" class="form-horizontal" action="<?php echo site_url('admin/edit_row/user_type/'.$etd_row->user_type_id)?>">
<div class="form-group">
<label class="col-sm-4 control-label">User Type Name</label>
<div class="col-sm-8"><input type="text" class="form-control" name="user_type_name" value="<?php echo $etd_row->user_type_name?>"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Edit changes</button>
</div>
</div>
</form>
<?php } ?>
on the foreach loop line, i am given error
Thanks in advance for your comments
Error
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/edit_user_type.php
Line Number: 18
Backtrace:
File: C:\wamp\www\gmf\application\views\edit_user_type.php
Line: 18
Function: _error_handler
File: C:\wamp\www\gmf\application\controllers\Display.php
Line: 170
Function: view
File: C:\wamp\www\gmf\index.php
Line: 315
Function: require_once
You'd get this error if $edit_table_data is not an array -- in this case probably a string.
My CI knowledge is a bit rusty, but I guess something along these lines may help you out:
$query = $this->db->select($table_name.'.*,country.country_name')
->join('country','country.country_id=user.user_country_id','left')
->where($table_name.'_id',$row_id)
->get($table_name);
if ($query->num_rows() === 0){
return []; // Make sure we're always returning an array.
// I'd rather handle this stuff in the view...
// Probably some kind of message that shows:
// that there are not results when $edit_table_data is not an array, otherwise loop.
}
return $query->result();
Or you could do something along these lines:
<?php
if (!is_array($edit_table_data)) {
echo 'No results here.';
} else {
foreach ($edit_table_data as $etd_row) { ?>
<form method="post" class="form-horizontal"
action="<?php echo site_url('admin/edit_row/user_type/' . $etd_row->user_type_id) ?>">
<div class="form-group">
<label class="col-sm-4 control-label">User Type Name</label>
<div class="col-sm-8"><input type="text" class="form-control" name="user_type_name"
value="<?php echo $etd_row->user_type_name ?>"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Edit changes</button>
</div>
</div>
</form>
<?php
}
}
?>
There does not seem to be a reason to call get_table_data twice, once with and once without $row_id, because you never use $table_data['$table_data'] in the view. In the interests of getting something that works that first call should be eliminated. The revised controller looks like this.
$table_data['edit_table_data'] = $this->display_model->get_table_data($table_name,$row_id) ;
$form_name='edit_'.$table_name;
$this->load->view('header');
$this->load->view($form_name,$table_data);
$this->load->view('footer');
The model code in the question is missing a curly brace } to close this statement.
if ($row_id != null)
{
So it is a little hard to tell exactly what you want to happen if $row_id is not provided. Without further information, my opinion is that get_table_data should not give the second argument a default value. In other words, the function should be defined without a default value for `$row_id - like this.
public function get_table_data($table_name, $row_id)
Without a default value for `$row_id a fatal error occurs if no value is provided. So the controller will need to make sure a value is provided.
Likewise, the controller should always check the return of the model is appropriate, or the model should always return something that the view can use.
get_table_data() contains a lot of repeated code - where($table_name.'_id', $row_id) and get($table_name)->result() appear three times each. By rearranging the logic, the repeating lines can be eliminated to make the function much more concise. Consider this version.
public function get_table_data($table_name, $row_id)
{
if($table_name === 'user')
{
$this->db
->select($table_name.'.*, country.country_name')
->join('country', 'country.country_id = user.user_country_id', 'left');
}
elseif($table_name === 'user_document')
{
$this->db
->select($table_name.'.* ,document.document_name')
->join('document', 'document.document_id = use_document.document_id', 'left');
}
return $this->db
->where($table_name."_id", $row_id)
->get($table_name)
->row();
}
The above returns data from any $table_name where $table_name."_id" == $row_id. Specific "select" and "join" clauses are added in the case of 'user' or 'user_document' tables.
Because you seem to be interested in only one row you should call row() instead of result().
It's important to know that db->row() will return NULL if no records are found. That fact can be used to test the model return and react appropriately. In this case, we do the check in the view. Because there is only one row. no foreach is needed.
<?php if(isset($edit_table_data)) { ?>
<form method="post" class="form-horizontal" action="<?php echo site_url('admin/edit_row/user_type/'.$edit_table_data->user_type_id) ?>">
<div class="form-group">
<label class="col-sm-4 control-label">User Type Name</label>
<div class="col-sm-8"><input type="text" class="form-control" name="user_type_name" value="<?php echo $edit_table_data->user_type_name ?>"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Edit changes</button>
</div>
</div>
</form>
<?php
}
else { ?> <div>No Data Available</div> <?php } ?>
I have been getting this error while submiting a form using codeigniter. I need help even though I have been following the documentation.
I am using 2.x version of codeigniter
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Products::$input‐
Filename: core/Model.php
Line Number: 52
Fatal error: Call to undefined function post() in /opt/lampp/htdocs/gamingplace/application/models/product_model.php on line 63
This is the code in my model
//add new product
public function addProduct(){
$data = array(
'category_id' => $this->input‐>post('category_id'),
'title' => $this->input‐>post('title'),
'description' => $this->input‐>post('description'),
'price' => $this->input‐>post('price')
);
if($_FILES['image']['error'] == 0){
$data['image'] = $this->upload->file_name;
return $this->db->insert('products',$data);
}
}
}
This is the code in my controller
public function addProduct()
{
if($_FILES['image']['error'] == 0){
//setting image preferences
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'jpg|png|jpeg|PNG|JPEG|JPG';
$config['overwrite'] = false;
$config['quality'] = '100%';
$config['remove_spaces'] = true;
$config['max_size'] = '90';// in KB
$this->load->library('upload',$config);
echo $this->input->post('image');
if( ! $this->upload->do_upload('image'))
{
$this->session->set_flashdata('message_failed', $this->upload->display_errors('', ''));
redirect('dashboard');
}else{
//Image Resizing
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['maintain_ratio'] = FALSE;
$config['width'] = 311;
$config['height'] = 162;
$this->load->library('image_lib',$config);
if ( ! $this->image_lib->resize()){
$this->session->set_flashdata('message_failed', $this->image_lib->display_errors('', ''));
}
//calling a model an its method to add a new product to the database
if($this->product_model->addProduct()){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
}
}
}
}
And my view
<!-- Modal -->
<script src="<?php echo base_url(); ?>assets/js/validation.js" charset="utf-8"></script>
<div class="modal fade" id="addProduct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Product</h4> <em>if the product category is not in the select option,
go to add category link to add category before adding this product</em>
</div>
<div class="modal-body">
<?php echo validation_errors('<div class="alert alert-danger">','</div>') ?>
<form role= "form" action="<?php echo base_url()?>products/addProduct" method="post" name="form" onsubmit="return validate(this)" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" class="form-control" placeholder="Enter name of product" required>
</div>
<div class="form-group">
<label>Brief Description of Product</label>
<textarea name="description" rows="8" cols="80" class="form-control">
This is a brand made by Gucci Company. Made of cotton, bla bla bla
</textarea>
</div>
<label>Select Category</label>
<div class="form-group">
<select class="form-control" name="category_id">
<?php foreach (get_categories_h() as $popular): ?>
<option value="<?php echo$popular->id?>"><?php echo $popular->name ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Enter or choose price</label>
<input type="number" id="price" class="form-control" name="price_old" required>
</div>
<input type="hidden" name="price" class="form-control" id="mainPrice"required>
<div class="form-group">
<input type="file" name="image" id="image" class="form-control" required accept="image/*" onChange="validateImage(this.value)">
</div>
<button type="submit" name="submit" class=" form-control btn btn-success">Add</button>
</form>
</form>
</div>
</div>
</div>
</div>
I think you may have a few issues going on with your code, but let's first focus on your question/error you mentioned. In your controller function, you are not passing the post to the model. You need to do something like this in the controller:
$addProduct = $this->product_model->addProduct($_POST);
if($addProduct){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
In the model function, you need to first let the function know there is an incoming parameter, then adjust how you are assigning the fields to the data array.
public function addProduct($post){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"]
);
return $this->db->insert('products',$data);
}
After that, I noticed that you have some other FILES logic in your model. That will likely error out, too. I believe that is going to have to be done in the controller, not the model. Once you do the upload in the controller, you can pass the file name into the model as well.
$upload_data = $this->upload->data();
$addProduct = $this->product_model->addProduct($_POST, $upload_data['file_name']);
if($addProduct){
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
Then, adjust the model.
public function addProduct($post, $fileName){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"],
'image' => $fileName
);
return $this->db->insert('products',$data);
}
Hope this helps.
I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.
I am using version CodeIgniter 2.1.4. I have problem on displaying form validation error. form validation is returning false but validation_errors() is not displaying any errors. I have tried to echo in controller and in view but no result. I am giving request through ajax.no php errors are thrown.
Controller:
<?php
class Dashboard extends Admin_Controller {
public function ajax_new_dist_center($id=NULL)
{
$this->load->model('dist_centre_m');
$this->load->helper(array('form', 'url'));
$this->load->library('Form_validation');
$validation = $this->dist_centre_m->rules;
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules($validation);
if ($this->form_validation->run() == TRUE)
{
if($this->dist_centre_m->create($id))
echo 'New centre created';
else
{
$this->output->set_status_header('404');
echo 'Given center not found';
}
}
else
{
$this->output->set_status_header('400');
echo 'validation Failed';
$this->load->view('alert_error');
}
}
}
View:
<?php echo validation_errors();?>
<p>Testing Error</p>
Model:
class dist_centre_m extends MY_Model {
protected $_table_name = 'distribution_centre';
protected $_primary_key = 'dis_id';
protected $_order_by = 'dis_id';
public $rules = array(
'name' => array(
'field'=>'name',
'label'=>'Center name',
'rules'=>'trim|required|xss_cleaned|min_length[3]|max_length[45]'
),
'street' => array(
'field'=>'street',
'label'=>'Street',
'rules'=>'trim|required|xss_cleaned|min_length[3]|max_length[45]'
),
'town' => array(
'field'=>'town',
'label'=>'Town',
'rules'=>'trim|required|min_length[3]|max_length[45]|required|xss_cleaned'
),
'postcode' => array(
'field'=>'postcode',
'label'=>'Postcode',
'rules'=>'trim|required|max_length[10]|required|xss_cleaned'
),
'tel' => array(
'field'=>'tel',
'label'=>'Telephone number',
'rules'=>'trim|valid|exact_length[11]|required|xss_cleaned'
),
);
public function __construct() {
parent::__construct();
$this->load->helper('security');
}
public function create($id=NULL){
$data = array(
'name' =>$this->input->post('name',true),
'street' =>$this->input->post('street',true),
'town' =>$this->input->post('town',true),
'postcode' =>$this->input->post('postcode',true),
'tel' =>$this->input->post('tel',true),
);
return $this->save($data,$id);
}
}
Output:
validation Failed
Testing Error
None of the related question is working please do not mark duplicate.
Update:
My Ajax request page:
<form id="new-center-form" method="post">
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Name"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for='street'>Street</label>
<input type="text" name="street" placeholder="Street"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="town">Town</label>
<input type="text" name="town" placeholder="Town"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" placeholder="Postcode"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Phone</label>
<input type="text" name="tel" placeholder="Telephone"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<button id="centre-submit" class="btn btn-primary pull-left">Save</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
var url_new_center = '<?php echo page_url('new-center') ?>';
$('#centre-submit').click(function(e){
e.preventDefault();
$.ajax({
url:url_new_center,
type:'post',
data: $('new-center-form').serialize()
}).done(function(response){
$('#infos').html(response);
$('#infos').slideDown();
$('.new-centre').slideUp();
}).fail(function(response){
$('#errors').html(response);
$('#errors').slideDown();
});
})
});
</script>
Finally after a long sleep I figured out.$this->form_validation->run() returns false when no $_POST data found and it will not set any errors to print. In my ajax request due to some errors it could not send any data. Thanks for curl I was able to test it.
update
data: $('new-center-form').serialize() // this was the error.
I made a typo here. this should be like this data: $('#new-center-form').serialize()
let me make your answer more clear.
It is not because no $_POST data found like you said,
it is actually because that there are no RELATED $_POST data that you have set rules for them in your model.
There may have been any other $_POST data exclude for those that you have set rules for:
'name' , 'street' , 'town' , 'postcode' , ' tel'
then the CI validator could not find any of the elements that rules have been set so the form_validation->run() will definitely return false
And certainly the validation_errors() will not show anything because there are nothing to apply the specified rules on.