codeIgniter form validation not working with file upload option - codeigniter

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]);

Related

page blashes while redirecting a form with codeigniter

I am learning to develop with codeigniter 3.1.8, for that I am confronted with a problem: I am confronted with a problem: I am redirected in a blank page and my errors do not display. please I would like to give you a hand
here is the function of the model for insertion
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_root extends CI_Model{
function isertion_root(){
$root=array(
'nom_admin'=>'$user_name',
'prenom_admin'=>'$user_prenom',
'email_admin'=>'$user_email',
'date_nais_admin'=>'$date_nais',
'date_inscription_admin'=>'NOW(),false',
'avatar_root'=>'$avatar_root',
'password_root'=>'$pssword_root'
);
$this->db->insert('root', $root);
}
/**
* #param $email
* #param $password
* #return bool
*/
function login_root($email,$password){
$this->db->select('*');
$this->db->from('root');
$this->db->where('email_admin',$email);
$this->db->where('password_root',$password);
if ($query=$this->db->get())
{
return $query->row_array();
}
else{
return false;
}
}
public function email_check($email_admin){
$this->db->select('*');
$this->db->from('root');
$this->db->where('email_admin',$email_admin);
$query=$this->db->get();
if($query->num_rows()>0){
return false;
}else{
return true;
}
}
}
here is the function of the controller for insertion
class Root extends CI_Controller{
function __construct(){
parent:: __construct();
$this->load->database();
$this->load->model('M_root');
$this->load->library('upload');
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->library('session');
}
public function index()
{
$this->load->view("register.php");
}
//debut fonction d'enregistrement
public function isertion_root(){
if($this->input->post('registersubmit')){
$config['upload_path'] = './assets/avatar-root/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if(!empty($_FILES['filefoto']['name']))
{
if ($this->upload->do_upload('filefoto'))
{
$gbr = $this->upload->data();
//Compress Image
$config['image_library']='gd2';
$config['source_image']='./assets/avatar-root/'.$gbr['file_name'];
$config['create_thumb']= FALSE;
$config['maintain_ratio']= FALSE;
$config['quality']= '60%';
$config['new_image']= './assets/avatar-root/'.$gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->form_validation->set_rules('nom_admin', 'nom administrateur', 'trim|required|min_length[3]|max_length[23]|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('prenom_admin', 'prenom administrateur', 'trim|required|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('email_admin', 'Email administrateur', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('date_nais_admin', 'Date de naissance administateur', 'trim|required');
$this->form_validation->set_rules('avatar_root', 'Avatar root', 'trim|required');
$this->form_validation->set_rules('password_root', 'password root', 'trim|required|min_length[8]|xss_clean');
$this->form_validation->set_rules('conf_password', 'confirm password', 'trim|required|matches[password]');
$root = array(
'nom_admin' => strip_tags($this->input->post('nom_admin')),
'prenom_admin' => strip_tags($this->input->post('prenom_admin')),
'email_admin' => strip_tags($this->input->post('email_admin')),
'date_nais_admin' => strip_tags($this->input->post('date_nais_admin')),
'avatar_root' => strip_tags($this->input->post('avatar_root')),
'password_root' => password_hash($this->input->post('password'),PASSWORD_DEFAULT)
);
print_r($root);
if ($this->form_validation->run() == TRUE)
{
$email_check=$this->M_root->email_check($root['email_admin']);
if($email_check){
$this->M_root->isertion_root($root);
$this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
redirect('root/login_view');
}
}
else{
$this->load->view('register');
}
}
}
}
}
//fin fonction d'enregistrement
view
<span style="background-color:red;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Creation d'un compte</h3>
</div>
<div class="panel-body">
<p class="alert-danger"><?php
$error_msg=$this->session->flashdata('error_msg');
if($error_msg){
echo $error_msg;
}
?></p>
<?php echo validation_errors(); ?>
<form role="form" method="post" enctype="multipart/form-data" autocomplete="off" action="<?php echo base_url().'Root/isertion_root'?>">
<fieldset>
<div class="form-group">
<?php echo form_error('nom_admin'); ?>
<input class="form-control" placeholder="Votre nom" name="nom_admin" value="<?php echo set_value('nom_admin'); ?>"type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Votre prenom" name="prenom_admin" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email_admin" type="email" autofocus>
</div>
<div class="form-group">
<div class="form-group">
<input class="form-control" placeholder="votre date de naissance" name="date_nais_admin" type="date" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="mot de passe " name="password_root" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="confirmez votre mot de passe" name="conf_password" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="votre photo" name="avatar_root" type="file" value="">
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Register" name="registersubmit" >
</fieldset>
</form>
<center><b>Already registered ?</b> <br></b>Login here</center><!--for centered text-->
</div>
</div>
</div>
</div>
</div>
</span>
Once i faced with this same problem i rectified by using this please try this.
ini_set('display_errors', 1);
Your original code contained many ifs and no elses. This mean if an if condition evaluates to false there is no reason for anything to be displayed.
This is a better way of doing it. If you keep everything all in one function and avoid redirects you can properly repopulate the input fields when an error occurs either from form validation or image uploading.
public function index() {
if ($this->input->post('registersubmit')) {
$this->form_validation->set_rules('nom_admin', 'nom administrateur', 'trim|required|min_length[3]|max_length[23]|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('prenom_admin', 'prenom administrateur', 'trim|required|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('email_admin', 'Email administrateur', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('date_nais_admin', 'Date de naissance administateur', 'trim|required');
$this->form_validation->set_rules('avatar_root', 'Avatar root', 'trim|required');
$this->form_validation->set_rules('password_root', 'password root', 'trim|required|min_length[8]|xss_clean');
$this->form_validation->set_rules('conf_password', 'confirm password', 'trim|required|matches[password]');
if ($this->form_validation->run()) {
$this->load->library('upload');
$config['upload_path'] = './assets/avatar-root/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if ($this->upload->do_upload('filefoto')) {
$gbr = $this->upload->data();
//Compress Image
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/avatar-root/' . $gbr['file_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '60%';
$config['new_image'] = './assets/avatar-root/' . $gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$root = array(
'nom_admin' => strip_tags($this->input->post('nom_admin')),
'prenom_admin' => strip_tags($this->input->post('prenom_admin')),
'email_admin' => strip_tags($this->input->post('email_admin')),
'date_nais_admin' => strip_tags($this->input->post('date_nais_admin')),
'avatar_root' => strip_tags($this->input->post('avatar_root')),
'password_root' => password_hash($this->input->post('password'), PASSWORD_DEFAULT)
);
// i have a feeling you are checking if an email already exists here
// you can use form validations is_unique function in the rules above and forgo this
if ($this->M_root->email_check($root['email_admin'])) {
$this->M_root->isertion_root($root);
$this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
redirect('root/login_view');
} else {
$this->session->set_flashdata('error_msg', 'bad email');
}
} else {
$this->session->set_flashdata('error_msg', $this->upload->display_errors());
}
}
}
$this->load->view("register.php");
}
You just have to change your form action to be blank so it submits to the same page.
Also in each input value except passwords you should do something like this:
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
This way the user won't lose their input when natural errors occur due to them entering wrong information or whatever.

Codeigniter 3 blog application: update() method deletes thumbnail

I am working on a basic blog application in Codeigniter 3.1.8.
There is a create post and an update post functionality.
When a post is created, there is the option to upload a post thumbnail, else a default image is displayed. In the post controller there is the method for creating posts:
public function create() {
// More code here
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('create');
$this->load->view('partials/footer');
} else {
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'default.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->create_post($post_image);
redirect('posts');
}
}
There is a method for updating posts:
public function update() {
// Form data validation rules
// irrelevant for the question suppressed
$id = $this->input->post('id');
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
$data = array('upload_data' => $this->upload->data());
$this->upload->do_upload();
$post_image = $_FILES['userfile']['name'];
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image);
redirect('posts/post/' . $id);
} else {
$this->edit($id);
}
}
In the Posts_model model:
public function update_post($id, $post_image) {
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body'),
'post_image' => $post_image,
'cat_id' => $this->input->post('category')
];
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
The edit post view:
<?php echo form_open_multipart(base_url('posts/update')); ?>
<input type="hidden" name="id" id="pid" value="<?php echo $post->id; ?>">
<div class="form-group <?php if(form_error('title')) echo 'has-error';?>">
<input type="text" name="title" id="title" class="form-control" placeholder="Title" value="<?php echo $post->title; ?>">
<?php if(form_error('title')) echo form_error('title'); ?>
</div>
<div class="form-group <?php if(form_error('desc')) echo 'has-error';?>">
<input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="<?php echo $post->description; ?>">
<?php if(form_error('desc')) echo form_error('desc'); ?>
</div>
<div class="form-group <?php if(form_error('body')) echo 'has-error';?>">
<textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"><?php echo $post->content; ?></textarea>
<?php if(form_error('body')) echo form_error('body'); ?>
</div>
<div class="form-group">
<select name="category" id="category" class="form-control">
<?php foreach ($categories as $category): ?>
<?php if ($category->id == $post->cat_id): ?>
<option value="<?php echo $category->id; ?>" selected><?php echo $category->name; ?></option>
<?php else: ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->name; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<label for="postimage">Upload an image</label>
<div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
The problem with the update() method is that, when editing a post, unless I replace it's existing thumbnail with a new one (in other words, if I let the file upload field empty), results in leaving the post without a thumbnail:
<img src="http://localhost/ciblog/assets/img/posts/">
What I have tried (not the best idea, I admit) is to fetch the name pg the file already existing in the posts table this way:
$data['post'] = $this->Posts_model->get_post($id);
$post_image = $data['post']->post_image;
But it gives the error Trying to get property of non-object.
What am I doing wrong?
Solved it:
In the edit post form, I have added an input of type hidden above the file input, in order to "capture" the posts image from the database:
<input type="hidden" name="postimage" id="postimage" value="<?php echo $post->post_image; ?>">
<label for="postimage">Upload an image</label><div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
</div>
In the Posts controller, I have replaced
$data = array('upload_data' => $this->upload->data());
$this->upload->do_upload();
$post_image = $_FILES['userfile']['name'];
with:
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
The code above means: if no new image is uploaded, write the name of the existing one in the posts table again, instead of writing nothing. If instead a new photo is uploaded, write the name of the new photo.

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

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...

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