I want to upload an image with first name and last name without refreshing the page in codeigniter - ajax

This is my controller
function edit_profile() {
// if (isset($_POST['submit']))
//{
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$name = $session_data['name'];
$uploaddata = null;
$config['upload_path'] = './assets/uploads/userpic';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$Img_name= strtotime(date("d-m-y H:i:s")).".jpg";
//$Img_name= strtotime(date("d-m-y H:i:s"));
$config['file_name']= $Img_name ;
$config['overwrite'] = "true";
$this->load->library('upload', $config);
if (!$this->upload->do_upload('documents')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploaddata = array('upload_data' => $this->upload->data());
}
$upload_data = $this->upload->data();
$file_name = $name;
$filepath1= $config['upload_path'];
if(!is_uploaded_file($_FILES['documents']['tmp_name'])) {
echo 'No upload';
$data = array(
'name' => $this->input->post('firstname'),
'lname' => $this->input->post('lastname')
);
}else
{
echo "file uploaded";
$data = array(
'name' => $this->input->post('firstname'),
'lname' => $this->input->post('lastname'),
'filepath'=> $Img_name,
'filename'=>$file_name
);
}
$this->load->model('update_model');
$this->update_model->update_entry($id, $data); //passing control to update_model
$session_data['name'] = $this->input->post('firstname');
$this->session->set_userdata('logged_in', $session_data); //settting sesssin values
if( $data)
{
$data['message']="Image Uploaded Successfully";
$this->load->view('endusers/endemp_edit_profile_view',$data);
}
//redirect('endusers/end_emp_home');
//}
}
This is my view
<?php echo form_open_multipart('endusers/editprofile/edit_profile');?>
<table width="auto" border="1" style="border-color: #bce8f1;"class="table table-bordered" >
<tbody>
<tr>
<td colspan="2"><input type="text" class="txt-field uname" name="firstname" placeholder="first name" required></td>
</tr>
<! ------ <tr>
<td colspan="2"><input type="text" class="txt-field pass" name="lastname" placeholder="last name" required ></td><br>
</tr>
<tr>
<tr>
<td valign="top">
<label for="curtexp" style="margin-top: 20px;padding-right: 7px;margin-left: 11px;"> Upload a Profile Picture </label> <label class="error" ></label>
<input type="file" name="documents" size="40" / style="margin-left: 9px;" placeholder="Profile Picture"><br><br>
</td>
</tr>
<tr>
<td colspan="8" style="text-align:center">
<br />
<div class="ee">
<input type="submit" class="btn btn-primary" value="Update" class="buttonmy2" / style="float: left; margin-bottom: 17px;">
<input type="Reset" class="btn btn-primary" value="Reset" class="buttonmy2" / style="float: left;margin-left: 10px;">
<?php echo validation_errors(); ?>
</div>
</td>
</tr>
</tbody>
</table>
</form>
This is my code in codeigniter for uploading a profile pic but it takes ma to log out to see the uploaded image .I want tom upload a image without logging out of my account and may be jusr refreshing the page

--This Jquery plugin will solve your problem
--More help http://malsup.com/jquery/form/#getting-started
<script src="http://malsup.github.com/jquery.form.js"></script>
$("#form_id").on('submit', (function (e) {
var options = {
url:'your URL', // target element(s) to be updated with server response
success:function(data){
alert('submitted');
}
$(this).ajaxSubmit(options);
e.preventDefault();
}));
Comment me if you need help...

Related

Ajax datatable is not inserting

I am studying about ajax datatabl. My AJAX datatable insert is not working. It has no error on console or whatsoever. It's just whenever I am inserting, the datatable is just refreshing. Is there anything that I missed? I have provided my codes below. Any help will be appreciated. Thank you very much.
This is the result whenever i'm adding. But it's not adding on database or whatsoever.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%">Name</th>
<th width="35%">Email</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<!-- <input type="file" name="user_image" id="user_image" /> -->
<!-- <span id="user_uploaded_image"></span> -->
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 3],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
if(name != '' && email != '')
{
$.ajax({
url:"<?php echo base_url() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
console.log(name);
console.log(email);
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
});
</script>
Controller:
function fetch_user(){
$this->load->model("profiles");
$fetch_data = $this->profiles->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = $row->name;
$sub_array[] = $row->email;
$sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"] )),
"recordsTotal" => $this->profiles->get_all_data(),
"recordsFiltered" => $this->profiles->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post("email.")
);
$this->load->model('profiles');
$this->profiles->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profiles");
$data = $this->profiles->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['name'] = $row->name;
$output['email'] = $row->email;
}
echo json_encode($output);
}
}
Model:
var $table = "userss";
var $select_column = array("id", "name", "email");
var $order_column = array(null, "name", "email", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("name", $_POST["search"]["value"]);
$this->db->or_like("email", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('id', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if($_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud()
{
$this->db->insert('userss', $data);
}
What is your database structure? Is the table called userss or users?
$this->db->insert('userss', $data); <--Possible typo?
You likely will need to use the inspect feature of your browser and look at any responses under the network tab to see any errors.

Multidimensional input with codeigniter not setting second array correct

On my controller function get form I get my banner images and I also use multidimensional array in my view
For some reason, the second banner_image title not showing but the value has been placed on the first array instead?
print_r($_POST)
Question How am I able to make sure that no matter how many banner images I select it can set the multidimensional array correct for each post.
public function getForm()
{
$banner_id = $this->uri->segment(5);
if ($banner_id)
{
$data['action'] = 'admin/design/banners/edit/' . $banner_id;
} else {
$data['action'] = 'admin/design/banners/add';
}
$banner_info = $this->admin_model_banner->getBanner($banner_id);
if ($this->input->post('banner_name')) {
$data['banner_name'] = $this->input->post('banner_name');
} elseif (!empty($banner_info)) {
$data['banner_name'] = $banner_info['banner_name'];
} else {
$data['banner_name'] = '';
}
if ($this->input->post('banner_status')) {
$data['banner_status'] = $this->input->post('banner_status');
} elseif (!empty($banner_info)) {
$data['banner_status'] = $banner_info['status'];
} else {
$data['banner_status'] = '';
}
$banner_images = array();
$banner_images_post = $this->input->post('banner_image');
if (isset($banner_images_post)) {
$banner_images = $this->input->post('banner_image');
} elseif (isset($banner_id)) {
$banner_images = $this->admin_model_banner->getBannerImages($banner_id);
}
$data['banner_images'] = array();
foreach ($banner_images as $banner_image)
{
if (is_file(FCPATH . 'image/' . $banner_image['image'])) {
$image = $banner_image['image'];
$thumb = $banner_image['image'];
} else {
$image = '';
$thumb = 'catalog/no_image.jpg';
}
$data['banner_images'][] = array(
'image' => $image,
'thumb' => $this->model_tool_image->resize($thumb, 100, 100),
'title' => $banner_image['title'],
'sort_order' => $banner_image['sort_order']
);
}
$data['placeholder'] = $this->model_tool_image->resize('catalog/no_image.jpg', 100, 100);
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('design/banner_form_view', $data);
}
View
<?php echo $header;?>
<div class="container">
<?php
$form = array(
'id' => '',
'role' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart($action, $form);?>
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Banner Status</label>
<div class="col-lg-10">
<input type="text" name="banner_name" class="form-control" placeholder="Enter Banner Name" value="<?php echo $banner_name;?>" size="50"/>
<?php echo form_error('banner_name', '<div class="text-danger" style="margin-top: 2rem;">', '</div>'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Banner Name</label>
<div class="col-lg-10">
<?php
$options = array('1' => 'Enabled', '0' => 'Disabled');
echo form_dropdown('banner_status', $options, $banner_status, array('class' => 'form-control'));
?>
</div>
</div>
<table id="images" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left">Title</td>
<td class="text-left">Image</td>
<td>Sort Order</td>
</tr>
</thead>
<tbody>
<?php $image_row = 0; ?>
<?php foreach ($banner_images as $banner_image) { ?>
<tr id="image-row<?php echo $image_row; ?>">
<td class="text-left">
<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" value="<?php echo $banner_image['title']; ?>" class="form-control">
</td>
<td class="text-left">
<a href="" id="thumb_image_<?php echo $image_row; ?>" data-toggle="image" class="img-thumbnail">
<img src="<?php echo $banner_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" />
</a>
<input type="hidden" name="banner_image[<?php echo $image_row; ?>][image]" value="<?php echo $banner_image['image']; ?>" id="input_image_<?php echo $image_row; ?>" /></td>
<td class="text-right"><input type="text" name="banner_image[<?php echo $image_row; ?>][sort_order]" value="<?php echo $banner_image['sort_order']; ?>" placeholder="Sort Order" class="form-control" /></td>
<td class="text-left">
<button type="button" onclick="$('#image-row<?php echo $image_row; ?>').remove();" class="btn btn-danger"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
<?php $image_row++; ?>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td colspan="3"></td>
<td class="text-left">
<button type="button" onclick="addImage();" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
</td>
</tr>
</tfoot>
</table>
</div>
<div class="panel-footer">
<div class="text-right"><button type="submit" class="btn btn-primary"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</button></div>
</div>
</div>
<?php echo form_close();?>
</div>
<script type="text/javascript">
var image_row = <?php echo $image_row; ?>;
function addImage()
{
html = '<tr id="image-row' + image_row + '">';
html += '<td class="text-left">';
html += '<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" class="form-control" value="">';
html += '</td>';
html += '<td class="text-left">';
html += '<a href="" id="thumb_image_' + image_row + '" data-toggle="image" class="img-thumbnail">';
html += '<img src="<?php echo $placeholder; ?>" data-placeholder="<?php echo $placeholder; ?>"/>';
html += '</a>';
html += '<input type="hidden" name="banner_image[' + image_row + '][image]" value="" id="input_image_' + image_row + '" />';
html += '</td>';
html += '<td class="text-right">';
html += '<input type="text" name="banner_image[' + image_row + '][sort_order]" value="" placeholder="Sort Order" class="form-control" />';
html += '</td>';
html += '</tr>';
$('#images tbody').append(html);
image_row++;
}
</script>
Solved
After doing some investigation I found problem was to do with
name="banner_image[<?php echo $image_row; ?>][title]"
On script, I forgot to add it like
name="banner_image[' + image_row + '][title]"
Working now

codeIgniter form validation not working with file upload option

I am trying this code but it is not working with file upload.
When there is no file uploading field it works fine but with file upload its not working.
Please help me.
form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('emp'); ?>
<form name="ajaxform" id="ajaxform" action="<?php echo base_url().'/emp/operation'?>" method="POST" enctype="multipart/form-data">
<table border="1">
<tr>
<th>Name</th>
<td><input type="text" name="name" value="<?php echo $name; ?>" size="50"/></td>
</tr>
<tr>
<th>Email </th>
<td><input type="text" name="email" value="<?php echo $email; ?>"/></td>
</tr>
<tr>
<th>Address</th>
<td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
</tr>
<tr>
<th>Phone</th>
<td><input type="text" name="phone" value="<?php echo $phone; ?>" /></td>
</tr>
<tr>
<th>Photo</th>
<td><input type="file" name="userfile" /></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" id="btn" value="<?php echo $submit; ?>" name="btn"/>
<input type="submit" id="simple-post" value="<?php echo $submit; ?>" name="simple-post"/>
</form>
</body>
Here is the controller code.
Emp.php
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name','required','callback_username_check');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[registration.email]');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'required');
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1800';
$config['max_width'] = '1924';
$config['max_height'] = '1924';
$new_name = time().$_FILES['userfile']['name'];
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload() OR $this->form_validation->run() == FALSE)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->emp_model->add_data();
$query['value']=$this->GetAll();
}
}
try this
if (null != ($_FILES['userfile']['tmp_name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'callback_checkPostedFiles');
}
And this function for validation
public function checkPostedFiles()
{
$file_name = trim(basename(stripslashes($_FILES['userfile']['name'])), ".\x00..\x20");
$file_name = str_replace(" ", "", $file_name);
if (isset($_FILES['userfile']) && !empty($file_name)) {
$allowedExts = array("jpeg", "jpg", "png"); // use as per your requirement
$extension = end(explode(".", $file_name));
if (in_array($extension, $allowedExts)) {
return true;
} else {
$this->form_validation->set_message('checkPostedFiles', "You can upload jpg or png image only");
return false;
}
} else {
$this->form_validation->set_message('checkPostedFiles', "You must upload an image!");
return false;
}
}
Check this sample code for image uploading :
Form :
<form method="post" action="" id="upload_file">
<div class="modal-body">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Profile Picture</label>
<input type="file" id="userfile" accept="image/*" name="userfile">
<p class="help-block">Requested size : 215*215</p>
</div>
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<button type="button" class="btn btn-default md-close" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
</div>
</div>
</form>
Include this js in your view.
Js for form submission
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url:'<?php echo base_url(); ?>profile/upload_file',
type: "POST",
fileElementId :'userfile',
success: function() {
alert("file uploaded!");
}
});
return false;
});
});
In controller
$userid = $session_data['id'];
$file_element_name = 'userfile';
$pathToUpload = '/var/www/html/uploads/' . $userid;
if ( ! file_exists($pathToUpload) )
{
$create = mkdir($pathToUpload, 0777);
if (!$create)
return;
}
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$this->upload->display_errors();
}
else
{
$data = $this->upload->data();
//$this->user->insert_file($data['file_name'], $userid);
$data = array(
'userPhoto' => $data['file_name']
);
$this->db->where('user_id', $userid);
$this->db->update('tbl_user_profile', $data);
}
//#unlink($_FILES[$file_element_name]);

You did not select a file to upload, file upload error in Codeigniter

I'm trying to add singer information with image. the information can be successfully added without image but if i try to insert data with image, error occurred with "You did not select a file to upload" message.
My controller function is this...
public function add_edit_singer($id = '')
{
if($this->input->post('save_singer_info')){
$post=$this->input->post();
$add=array(
'name'=>$post['sname'],
'bio'=>$post['bio']
);
$img1=$_FILES['photo']['name'];
if($img1){
$config['upload_path'] = 'images/singer/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$error = $this->upload->display_errors();
$this->session->set_flashdata('info',$error);
redirect('admin/singer_manager');
}
$data = array('upload_data' => $this->upload->data());
$image = $data['upload_data']['file_name'];
$add['image']=$image;
}
else{
$add['image']='no_image.jpg';
}
$table='tbl_singer';
if($this->singer_manager->add($add,$table)){
$this->session->set_flashdata('info',"Artist/Band Information Added Successfully.");
redirect('admin/singer_manager');
}
else{
redirect('admin/singer_manager');
}
}
else{
$data['main_content']='admin/singer/add_edit_singer_view';
if($id != '')
$data['editdata'] = $this->common_model->get_where('tbl_singer', array('id' => $id));
$this->load->view('admin/include/template_view',$data);
}
}
my Model function is...
function add($data,$table){
$name = $data['name'];
$res = $this->db->insert($table,$data);
if($res)
{
return true;
}
else
{
return false;
}
}
and my Form is...
<form role="form" enctype="multipart/form-data" action="<?php echo base_url('admin/singer_manager/add_edit_singer/' . $id); ?>"
method="post"
id="user_form">
<table class="table table-hover">
<tr>
<td>Singer Name</td>
<td>
<input type="text" class="form-control required" name="sname"
value="<?php if (isset($name)) {
echo $name;
} ?>"/>
</td>
</tr>
<tr>
<td>Bio</td>
<td>
<textarea class="form-control required" name="bio">
<?php if (isset($bio)) {
echo $bio;
} ?>
</textarea>
</td>
</tr>
<tr>
<td>Image</td>
<td>
<?php if (isset($image)) {?>
<div class="row">
<div class="col-xs-6 col-md-4">
<a href="<?php echo base_url().'images/singer/'.$image;?>" class="thumbnail">
<img src="<?php echo base_url().'images/singer/'.$image;?>" width="120" height="140" id="img_prev" />
</a>
</div>
</div>
<?php
} ?>
<input type="file" name="photo" size="20" />
</td>
</tr>
<tr>
<td colspan="2">
<?php if (isset($id)) { ?><input type="hidden" name="id" value="<?php echo $id; ?>" /><?php } ?>
<input type="submit" class="btn btn-success" id="btn_save" name="save_singer_info"value="Save"/>
<input type="reset" class="btn btn-info" id="reset"/>
<input type="button" class="btn btn-danger" value="Cancel"onclick="history.go(-1)"/>
</td>
</tr>
</table>
</form>
change
$this->upload->do_upload()
to
$this->upload->do_upload('photo')
may be it solve the problem

update record with the form - Codeigniter 2.1

i have some problem with update in CI 2.1
I followed the user guide "mini-tut" for create e news, but i cant understand how to update a record with a form.
my update models is:
// update dei record
public function update_news($id)
{
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text')
);
$this->db->where('id', $id);
$this->db->update('news', $data);
}
how can i make the controller for update?? i try:
public function update($id)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update an intem';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/update');
$this->load->view('templates/footer');
}
else
{
$this->news_model->update_news($id);
$this->load->view('news/success');
}
}
but i display a 404() page...
the views for update is:
<h2>Update an item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="slug">Slug</label>
<input type="input" name="slug" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update an item" />
</form>
any one can help me how do a "simnple" update for understand a CI logic?
If I understand what you want, then you should just pass the $this->input->post(x) to the model from your controller.
I personally have been using it like this:
Controller:
$data = array(
'title' => $this->input->post('title'),
'text' => $this->input->post('text'),
'slug' => $this->input->post('slug'),
);
if($this->my_model->exists($id)) {
$this->my_model->update($id, $data);
} else {
$this->my_model->insert($data);
}
And your Model should look like:
// update dei record
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update('news', $data);
}
Your controller uses the first segment as an argument of the controller method:
public function update($id)
You can also try using
$id = $this->uri->segment(3);
//Controller
public function update($id)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update an intem';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
$data['news'] = $this->news_model->get_news_by_id($id);
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
$this->load->view('templates/footer');
}
else
{
$this->load->helper('url');
$this->news_model->update_news($id);
redirect('/news', 'refresh');
}
}
//Model
public function update_news($id)
{
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('title'),
'text' => $this->input->post('text')
);
$this->db->where('id', $id);
$this->db->update('news', $data);
}
View
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $news[0]['title'];?>" /><br />
<input type = "hidden" name="id" value="<?php echo $news[0]['id'];?>" />
<label for="text">Text</label>
<textarea name="text"><?php echo $news[0]['text'];?></textarea><br />
<input type="submit" name="submit" value="Create news item" />
To add a page in code igniter
I will give you the example which i have done
Model:
function add()
{
$name=$_POST['name'];
$department=$_POST['dept'];
$degree=$_POST['degree'];
$mark=$_POST['mark'];
$this->db->query("INSERT INTO `simple`(name,department,degree,mark) VALUES('$name','$department','$degree','$mark')");
}
Controller:
public function add()
{
$this->load->model('modd');
$this->modd->add();
$this->load->view('add');
}
Views :
add.php
<form method="post" action="<?php base_url();?>index.php/contr/add">
<table>
<?php echo form_open('contr/add');?>
<tr>
<th>Name</th>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<th>Department</th>
<td><input type="text" name="dept" /></td>
</tr>
<tr>
<th>Degree</th>
<td><input type="text" name="degree" /></td>
</tr>
<tr>
<th>Marks</th>
<td><input type="text" name="mark" /></td>
</tr>
<tr>
<td><input type="submit" name="add" value="Add" /></td>
<?php echo form_close(); ?>
<td>
<input type="button" value="view" />
</td>
</tr>
</table>

Resources