Codeigniter - How to add Images to my CRUD methods? - php

I am working on my second CI application. I have created some simple CRUD methods in my controller. My client has requested that each record includes an image. I have searched the forums and other resources for help but haven’t had much luck.
I have managed to upload files into a directory using the File Uploading Class, my problem though is how to associate the uploaded file/s with the relevant record.
Here are the relevant parts of my MVC.., any help/point in the right direction would be appreciated.
View - admin/locationEdit.php
<form method="post" action="<?php echo $action; ?>">
<div class="data">
<table>
<tr>
<td width="30%">ID</td>
<td><input type="text" name="id" disabled="disable" class="text" value="<?php echo $this->validation->id; ?>"/></td>
<input type="hidden" name="id" value="<?php echo $this->validation->id; ?>"/>
</tr>
<tr>
<td valign="top">Name<span style="color:red;">*</span></td>
<td><input type="text" name="name" class="text" value="<?php echo $this->validation->name; ?>"/>
<?php echo $this->validation->name_error; ?></td>
</tr>
<tr>
<td valign="top">Address<span style="color:red;">*</span></td>
<td><input type="text" name="address" class="text" value="<?php echo $this->validation->address; ?>"/>
<?php echo $this->validation->address_error; ?></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save"/></td>
</tr>
</table>
</div>
</form>
Controller - location.php
function add(){
// set validation properties
$this->_set_fields();
// set common properties
$data['title'] = 'Add new location';
$data['message'] = '';
$data['action'] = site_url('admin/location/addLocation');
$data['link_back'] = anchor('admin/location/index/','Back to list of locations',array('class'=>'back'));
// Write to $title
$this->template->write('title', 'Admin - Add New Location!');
// Write to $sidebar
$this->template->write_view('content', 'admin/locationEdit', $data);
// Render the template
$this->template->render();
}
function addLocation(){
// set common properties
$data['title'] = 'Add new location';
$data['action'] = site_url('admin/location/addLocation');
$data['link_back'] = anchor('admin/location/index/','Back to list of locations',array('class'=>'back'));
// set validation properties
$this->_set_fields();
$this->_set_rules();
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$path_to_uploads='./uploads';
$config['upload_path'] = $path_to_uploads;
$this->load->library('upload', $config);
$upload_data=$this->upload->data();
$file_name=$upload_data['file_name'];
$full_file_path = $path_to_uploads.'/'.$file_name;
// run validation
if ($this->validation->run() == FALSE){
$data['message'] = '';
}else{
// save data
$location = array('name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'image_url' => $full_file_path);
$id = $this->locationModel->save($location);
// set form input name="id"
$this->validation->id = $id;
// set user message
$data['message'] = '<div class="success">add new location success</div>';
}
// Write to $title
$this->template->write('title', 'Admin - Add New Location!');
// Write to $sidebar
$this->template->write_view('content', 'admin/locationEdit', $data);
// Render the template
$this->template->render();
}

Within your upload function, get the path of the uploaded file:
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$path_to_uploads='./uploads';
$config['upload_path'] = $path_to_uploads;
$this->load->library('upload', $config);
//add this
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$error = $this->upload->display_errors();
echo "<script>alert($error);</script>";
}else{
$upload_data=$this->upload->data();
$file_name=$upload_data['file_name'];
$full_file_path = $path_to_uploads.'/'.$file_name;
}
then you can return $full_file_path back to the method that called it and insert it into the db, or just insert directly.

Related

How to upload data to database using codeigniter

I want to upload the image to database using codeigniter. It saved to database but the image didn't send to the folder path i've set and only the image_path are saved to the database. Can you tell me what to do or anything I did wrong? Here's my code:
* Controller *
function saveEvent(){
$config = [
'upload_path' => './assets/img',
'allowed_types' => 'gif|png|jpg|jppeg'
];
$this->load->library('upload', $config);
$this->form_validation->set_error_delimiters();
$this->upload->do_upload();
// var_dump('asd'. $this->upload->do_upload());
// if($this->upload->do_upload()){
$datas = $this->input->post('eventimage');
$info = $this->upload->data();
$image_path = "./assets/img/".$info['raw_name'].$info['file_ext'];
$data['cal_events_image'] = $image_path;
$data['cal_events_name'] = $this->input->post('eventname');
unset($data['submit']);
$this->load->model('CalendarModel');
if($this->CalendarModel->eventinsertdata($data)){
echo "success";
}else{
echo " fail";
}
* View *
<form action="<?php echo base_url('index.php/CalendarController/saveEvent');?>" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<table class="table">
<tr>
<td>Event Type</td>
<td><input type="text" name="eventname"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" name="eventimage"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submitevent" value="Add Event" class="btn btn-success"></td>
</tr>
</table>
</form>
* Model *
function eventinsertdata($data){
return $this->db->insert('table', $data);
return $this->db->insert('dev_adkt_events_type', $data);
echo 'hahay';
}
Thank you guys in advance. Hope you could help me with this.
I already solve it! here is my answer and it works!
Controller
function saveEvent(){
$config = array(
'upload_path' => './assets/img',
'allowed_types' => 'gif|png|jpg|jppeg'
);
get_instance()->load->library('upload', $this->config);
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->form_validation->set_error_delimiters();
if($this->upload->do_upload('eventimage')){
$data = $this->input->post('eventimage');
$info = $this->upload->data();
// var_dump($info);
$image_path = "/assets/img/".$info['raw_name'].$info['file_ext'];
$datas['cal_events_image'] = $image_path;
$datas['cal_events_name'] = $this->input->post('eventname');
unset($data['submit']);
$this->load->model('CalendarModel');
if($this->CalendarModel->eventinsertdata($datas)){
// echo "success";
redirect($_SERVER['HTTP_REFERER']);
}else{
echo $this->upload->display_errors();
}
}else{
// echo 'shit';
echo $this->upload->display_errors();
}
}

CodeIgniter Upload Image no input

I am trying to implement CodeIgniter's upload library. But everytime I tried to upload, it keeps on saying that I haven't selected a file to upload.
Here is the code:
View:
<form action="<?= base_url().'principal/updateuniform' ?>" method="post">
<h3 style="text-align:center">Polo</h3>
<input type="hidden" name="imageid" value="<?= $img_id ?>">
<input type="hidden" name="imagename" value="<?= $img_name ?>">
<input type="file" name="imagefile" accept="image/*" /><br>
<button type="submit" class="btn btn-gold"><span class="glyphicon glyphicon-upload" aria-hidden="true"></span> Upload</button>
</form>
Upload function:
function updateuniform(){
$img_id = $this->input->post('imageid');
$img_name = $this->input->post('imagename');
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = 3000;
$config['max_height'] = 4000;
$config['overwrite'] = TRUE;
$config['file_name'] = $img_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = $this->input->post('imagefile');;
$id = $this->session->userdata('id');
$user['user'] = $this->UsersModel->select_principal($id);
if (!$this->upload->do_upload($img)){
$data['error'] = $this->upload->display_errors();
$data['uniforms'] = $this->InfoModel->getUniforms();
$this->load->view('include/header_principal',$user);
$this->load->view('principal/manage_uniforms', $data);
$this->load->view('include/footer_principal');
} else {
$img_path = 'images/'.$this->upload->data('orig_name');
$data['success'] = 'Uniforms has been updated.';
$this->InfoModel->updateUniform($img_path);
$this->load->view('include/header_principal',$user);
$this->load->view('principal/manage_uniforms', $data);
$this->load->view('include/footer_principal');
}
}
I also tried to echo the $img and it's displaying the file name.
$this->upload->do_upload($img)
The param should be the filedname,like:
$this->upload->do_upload('imagefile')
Add enctype="multipart/form-data" in your form tag of view this allows you to get $_FILE value and This will solve your issue I guess

Insert each “checked” check box values from multiple checkboxes to the database using codeigniter

i am working in codeigniter php. i want to insert multiple rows for each checked checkbox value with oyhers value. t tried to do it. but it shows me database array error.
In view :
Category Name:
<?php
foreach($result as $aresult)
{
?>
<input type="checkbox" name="category_name[]" value="<?php echo $aresult->category_name;?>" /> <?php echo $aresult->category_name;?> <br>
<?php
}
foreach($area as $aresult1)
{
?>
<input type="checkbox" name="category_name[]" value="<?php echo $aresult1->category_name;?>" /> <?php echo $aresult1->category_name;?> <br>
<?php
}
?>
<tr>
<td>Content Headline:</td>
<td>
<input type="text" required="1" name="content_headline" tabindex="3" placeholder="Content Headline" size="80"/>
</td>
</tr>
<tr>
<td>Picture</td>
<td>
<input type="file" name="image" tabindex="8"/>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn" value="Save" tabindex="9"/></td>
</tr>
Controller:
public function savecontent()
{
date_default_timezone_set('Asia/Dhaka');
foreach($this->input->post('category_name') as $rm){
$data=array(
$now = date("Y-m-d H:i:s"),
$data['admin_id']=$this->session->userdata('admin_id'),
$data['category_name']=$this->input->post('category_name',true),
$data['content_headline']=$this->input->post('content_headline',true),
$this->load->library('upload');
$config['upload_path'] = './images/news_images/';
$config['allowed_types'] = 'gif|jpg|png|mp3';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '720';
$error = '';
$udata = '';
$udata1 = '';
$udata2 = '';
$udata3 = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
}
else {
$udata = array('upload_data' => $this->upload->data());
$data['image'] = "images/news_images/" . $udata['upload_data']['file_name'];
}
);
}
$this->co_model->save_content($data);
}
Model:
public function save_content($data)
{
$this->db->insert('content',$data);
}
this code shows me database array error. so now how i solve this problem?
Move $this->co_model->save_content($data); inside foreach loop.
Try this code
public function savecontent()
{
date_default_timezone_set('Asia/Dhaka');
foreach($this->input->post('category_name') as $rm)
{
$data=array();
$now = date("Y-m-d H:i:s"),
$data['admin_id']=$this->session->userdata('admin_id'),
$data['category_name']=$this->input->post('category_name',true),
$data['content_headline']=$this->input->post('content_headline',true),
$this->load->library('upload');
$config['upload_path'] = './images/news_images/';
$config['allowed_types'] = 'gif|jpg|png|mp3';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '720';
$error = '';
$udata = '';
$udata1 = '';
$udata2 = '';
$udata3 = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$udata = array('upload_data' => $this->upload->data());
$data['image'] = "images/news_images/" . $udata['upload_data']['file_name'];
}
$this->co_model->save_content($data);
}
}

Uploading multiples files in CodeIgniter using plain PHP

I am new to CodeIgniter. I've tried uploading my files using as follows:
(createAlbum.php)
<form method="post" action="createAlbum_db.php" enctype="multipart/form-data">
<table>
<tr>
<td>Album Name: </td><td><input type="text" name="album_name"></td>
</tr>
<tr>
<td>Photos for album: </td><td><input type = "file" name="photos[]" multiple="true"></td>
</tr>
<tr>
<td><input type="submit" value="Create Album"></td>
</tr>
</table>
</form>
(createAlbum_db.php)
for ($i=0; $i < count($_FILES['photos']['name']);$i++) {
if (move_uploaded_file(base_url().'assets/images/'.$_FILES['photos']['name'][$i],$_FILES['photos']['tmp_name'][$i])) {
echo '<br>success';
} else {
echo '<br>Failure';
echo $_FILES['photos']['error'][$i];
}
}
My assets directory lies in the same directory where application and system files reside.
What I am not being able to figure out is what should I keep in
move_uploaded_file(**DESTINATION????**,$_FILE['photos']['tmp_name']);
I have gone through most of the post and I found CodeIgniter's native uploader class difficult to use.
Codi. provides upload function for that
<?php
$config['upload_path'] = // Here Goes Path;
$config['allowed_types'] = // Here Goes allowed file types;
$config['max_size'] = // you can validate max. size;
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
echo $this->upload->display_errors();
}
else
{
$img = $this->upload->data();
$img_name = $img['file_name'];
}
?>
Just Like this, you can upload single file....
Since you need path on server use realpath('assets/images/') instead of base_url().

Codeigniter form submit with file upload

im trying to write a code where i can submit a form enter the contents in a database, at the same time perform a file upload and have it stored in a folder inside my server
the folder location is called uploads which is located at the root of my site
here is my code
controller (site.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->model("site_model");
$this->load->helper(array('form', 'url'));
}
public function cmain($type,$page)
{
$data = $this->_initialize_data(); //this is just a bunch of variables that im calling in another function
$data['type'] = $type;
$data['page'] = $page;
$this->load->vars($data);
$this->load->view('site/cmain');
}
public function m1()
{
$this->load->library('upload', $config);
if(isset($_POST['m1']))
{
$suffix = $this->input->post("suffix");
$fn = $this->input->post("fn");
$mn = $this->input->post("mn");
$ln = $this->input->post("ln");
$newdata = array('suffix'=>$suffix,
'fn'=>$fn,
'mn'=>$mn,
'ln'=>$ln,
);
//this code is for the file upload
$config['upload_path'] = 'uploads';
$config['allowed_types'] = '*';
$this->load->library('upload', $config);
$data = array('upload_data' => $this->upload->data());
//end of file upload codes
$this->db->insert('myself', $newdata);
redirect(base_url() . "site/complaint");
}
}
view (cmain.php)
<form action="<?php echo base_url();?>site/m1" name="details" id="details" method="post" enctype="multipart/form-data">
<table class='table' width="100%">
<tr>
<td colspan='2'>
<b><font color="#3B608C">Personal Information</font></b>
</td>
</tr>
<tr>
<td>
Suffix (e.g. Jr., III)
</td>
<td>
<input type="text" name="suffix" id="suffix" value="">
</td>
</tr>
<tr>
<td>
First Name*
</td>
<td>
<input type="text" name="fn" id="fn" value="">
</td>
</tr>
<tr>
<td>
Middle Name*
</td>
<td>
<input type="text" name="mn" id="mn" value="">
</td>
</tr>
<tr>
<td>
Last Name*
</td>
<td>
<input type="text" name="ln" id="ln" value="">
</td>
</tr>
</table>
<table>
<tr>
<td width="50%">
Please attach documents pertinent to these complaints. <br>
(Attach a zip file if more than one document)<br>
</td>
<td align="center">
<input name = "userfile" type="file" class="input-xlarge" id = "userfile" />
</td></tr>
</table>
<input type="submit" value="Submit Form" class="pull-right" id="submit" name="m1"/>
</form>
the form posts properly in the database like the suffix,fn,ln and mn
however the file upload isnt working
i tried my best to follow what the codeigniter docs samples and only got the lines i think i needed
am i doing something wrong?
thanks
finally got it working
i used this for the file upload part
//start of file upload code
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
//end of file upload code
and changed the
<form action="<?php echo base_url();?>site/m1" name="details" id="details" method="post" enctype="multipart/form-data">
into
<?php echo form_open_multipart('site/c_upload');?>
I think you must have to set file upload preference
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
Form Helper
$this->load->helper(array('form', 'url'));
For further detail have a look at my blog post
Did you set writing permissions for 'uploads' folder? (example: php.net/manual/en/function.chmod.php)
Always do test driven development. I got below code block from this url
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}

Categories