How to add multi images into database - php

I am trying to add multiple images one for the banner images other multiple images for the gallery images but when I try to add an image it gives me the error:
array to string conversation.
I want to add one image into the same table and other images into the different table so when I will show record into my view I can one banner image easily.
I will be very thankful if someone help me in this.
so here is the my view.
<div class="col-lg-12">
<label for="main image">Upload Main Image: </label><br>
<input type="file" name="image_file">
</div><br><br><br>
<div class="col-lg-12">
<label for="Image name">Upload Mutiple Images:</label><br>
<input type="file" required name="image_name[]" multiple/><br>
</div>
// Model
function addnews($data, $id ='')
{
$title = $this->input->post('title');
$address = $this->input->post('address');
$city = $this->input->post('city');
$zip = $this->input->post('zipcode');
$type = $this->input->post('propertytype');
$status = $this->input->post('status');
$price = $this->input->post('price');
$description = $this->input->post('Description');
$userfile = $this->input->post('[image_file]');
$bedrooms = $this->input->post('bedrooms');
$rooms = $this->input->post('rooms');
$bath = $this->input->post('bathroom');
$garages = $this->input->post('gerages');
$date = $this->input->post('date');
$amenities = implode(',',$this->input->post('check'));
$w = array (
'title' => $title,
'address' => $address,
'city' => $city,
'zip' => $zip,
'type' => $type,
'status' => $status,
'description' => $description,
'bedrooms' => $bedrooms,
'rooms' => $rooms,
'price' => $price,
'userfile' => $data,
'bath' => $bath,
'date' => $date,
'garages' => $garages,
'amenities' => $amenities
);
$this->db->insert_batch("property", $w);
$id = $this->db->insert_id();
foreach ($data as $row) { // here data is from parameter
$data1[] = array(
'property_id' => $id, //Insert Inserted id
'image_name' => $row['file_name'] // this line is changed
);
}
}
// My controller.
public function addlisting()
{
$this->load->library('upload');
$config['upload_path']='./uploads';
$config['allowed_types']='*';
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image_file')) {
$this->session->set_flashdata('msg',"Failed To Apply. Please Check All The Fields.");
redirect(site_url('Welcome/add_listing'));
} else {
$fd = $this->upload->data();
$fn = $fd['file_name'];
//$this->User_model->addnews($fn);
$image = array();
$ImageCount = count($_FILES['image_name']['name']);
for ($i = 0; $i < $ImageCount; $i++) {
$_FILES['file']['name'] = $_FILES['image_name']['name'][$i];
$_FILES['file']['type'] = $_FILES['image_name']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image_name']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['image_name']['error'][$i];
$_FILES['file']['size'] = $_FILES['image_name']['size'][$i];
// File upload configuration
$uploadPath = './uploads';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if ($this->upload->do_upload('file')) {
// Uploaded file data
$imageData = $this->upload->data();
$uploadImgData[$i]['file_name'] = $imageData['file_name'];
} else {
$this->session->set_flashdata('msg',"Error while uploading Data");
// $this->User_model->addnews($uploadImgData);
redirect(site_url('Welcome/add_listing'));
}
}
if (!empty($uploadImgData)) {
//Insert files data into the database
$this->User_model->addnews($uploadImgData);
$this->User_model->addnews($fn);
// $query = implode(",",$uploadImgData);
// $insert = $this->User_model->add($uploadImgData);
$this->session->set_flashdata('msg',"Property Uploaded successfully");
redirect('Welcome/add_listing');
}
}

try to change name or config array
public function add_model()
{
$this->before_login();
$data = array();
$data['mode'] = "ADD";
$db_name = 'para';
$table = 'models';
$sess = $this->session->userdata('admin');
$data['a_name'] = $sess['name'];
$data['record'] = $this->Paramodel->select('brand','brand_name,id');
if($this->input->post('submit'))
{
$this->Database->add_new_model($table,$db_name);
foreach($_POST as $key=>$value)
{
$$key=trim($value);
}
// Form Validation Run
if($this->form_validation->run('add_model'))
{
if(strlen($_FILES['model_display_picture']['name']) > 0)
{
$config['upload_path'] = './assets/Model/';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 2048;
$config['encrypt_name'] = TRUE;
// directry Path
$this->load->library('upload',$config);
$slug = $this->clean_url($model_name);
$this->upload->initialize($config);
if($this->upload->do_upload('model_display_picture'))
{
$result=$this->last_record('models')[0]['setord'];
// echo "<pre>";
// print_r($result);
// exit;
if($result == "" ){ $last_setord_no = 1; }else{ $last_setord_no = $result+1; }
$image_path = './assets/Model/'.$this->upload->data('file_name');
// INSERT DATA
$ins['brand_id'] = $brand_id;
$ins['model_type'] = $model_type;
$ins['model_name'] = $model_name;
$ins['model_description'] = $model_description;
$ins['model_display_image'] = $image_path;
$ins['status'] = $status;
$ins['slug'] = $slug;
$ins['setord'] = $last_setord_no;
$ins['meta_title'] = addslashes($meta_title);
$ins['meta_descryption'] = $meta_description;
$ins['meta_keywords'] = $meta_keywords;
$ins['u_create_date'] = date('Y-m-d H:i:s');
// INSERT QUERY
$insert = $this->Paramodel->insert('models',$ins);
$insert_id = $this->db->insert_id();
$this->_create_thumbs($this->upload->data('file_name'));
// INSERT SUCCESS CONDITION
if( $insert == 1 )
{
$count = count($_FILES['model_images']['name']);
if( $count > 0)
{
$this->Database->model_image('model_image');
for($i = 0 ; $i < $count ; $i++ )
{
$_FILES['single']['name'] = $_FILES['model_images']['name'][$i];
$_FILES['single']['type'] = $_FILES['model_images']['type'][$i];
$_FILES['single']['tmp_name'] = $_FILES['model_images']['tmp_name'][$i];
$_FILES['single']['size'] = $_FILES['model_images']['size'][$i];
$_FILES['single']['error'] = $_FILES['model_images']['error'][$i];
$config1['upload_path'] ='./assets/Model/';
$config1['allowed_types'] = 'jpg|jpeg|png';
$config1['max_size'] = 2048;
$config1['encrypt_name'] = TRUE;
// echo "<pre>";
// print_r($config1);
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
// echo "<pre>";
// print_r($_FILES['single']);
// echo "------------------";
if($this->upload->do_upload('single'))
{
// echo "<pre>";
// print_r($config1);
$images_path = './assets/Model/'.$this->upload->data('file_name');
$ins_up['model_id'] = $insert_id;
$ins_up['model_image'] = $images_path;
$result = $this->Paramodel->insert('model_image',$ins_up);
$this->_create_thumbs($this->upload->data('file_name'));
if($result == 1)
{
$this->session->set_flashdata('insert','Model Insert SuccessFully.');
redirect('manage-models');
}
}
else
{
$data['error'][$i] = array('error' => $this->upload->display_errors());
}
}
}
}
}
else
{
$data['error'][$i] = array('error' => $this->upload->display_errors());
}
}
}
}
$this->load->view('admin/add_model',$data);
}
my code is this try it.

Related

Trying to send the file link to mail but only get one file

Trying to send the file link to mail but only get one file. How can I take all file links and send?
public function uploadpath() {
$this->load->library('upload');
// If files are selected to upload
if (!empty($_FILES['files']['name']) && count(array_filter($_FILES['files']['name'])) > 0) {
$filesCount = count($_FILES['files']['name']);
for ($i = 0; $i < $filesCount; $i++) {
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
$config['upload_path'] = './assets/AddmissionDocument';
$config['allowed_types'] = 'pdf|jpg|jpeg|JPEG';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if (!$this->upload->do_upload('file')){
return false;
}
else {
$file=array($_FILES['files']['name'][$i]);
return $file;
}
}
}
}
$files = $this->uploadpath();
$this->sending($files);
$this->session->set_userdata(array('idf' => $fid, 'idL' => $result, 'StudentN' => $e, 'course' => $b));
$this->sucessdata();
}
public function sending($files) {
$ADMN = $this->session->userdata('ADMISSIONNO');
$MOE = $this->session->userdata('modeofedu');
$CC = $this->session->userdata('Course');
$LCQ = $this->session->userdata('LastQualifiedCourse');
$UB = $this->session->userdata('UniversityBoard');
$SN = $this->session->userdata('studentname');
$DOB = $this->session->userdata('dob');
$G = $this->session->userdata('gender');
$OCC = $this->session->userdata('Occupation');
$FN = $this->session->userdata('FatherName');
$MN = $this->session->userdata('MotherName');
$NFS = $this->session->userdata('NameofSpouse');
$SCC = $this->session->userdata('scountryCode');
$SMN = $this->session->userdata('sMobileNo');
$FCC = $this->session->userdata('fcountryCode');
$FMN = $this->session->userdata('fMobileNo');
$NCC = $this->session->userdata('ncountryCode');
$NMN = $this->session->userdata('nMobileNo');
$N = $this->session->userdata('Nationality');
$NIDT = $this->session->userdata('Nidtype');
$NIDN = $this->session->userdata('Nidnumber');
$PASNO = $this->session->userdata('PassportNumber');
$EMID = $this->session->userdata('EmiratesId');
$EMAID = $this->session->userdata('Email');
$ADD = $this->session->userdata('Address');
$NADD = $this->session->userdata('NAddress');
$NADDC = $this->session->userdata('NAddressCity');
$NADDS = $this->session->userdata('NAddressState');
$subject = "Application Form Submitted by" . $SN;
$message = "-----------------------------------------------------------------
ADMISSION NO : $ADMN
-----------------------------------------------------------------
Mode of Education : $MOE
Course : $CC
Student Name : $SN
Date of Birth : $DOB
Gender : $G
Occupation : $OCC
Father Name : $FN
Mother Name : $MN
Name of Spouse : $NFS
Mobile No : $SCC -$SMN
Mobile No : $FCC -$FMN
Mobile No : $NCC -$NMN
Nationality : $N
National ID : $NIDT Type ID Number : $NIDN
Passport Number : $PASNO
Emirates Id : $EMID
Email : $EMAID
-----------------------------------------------------------------
Address in UAE : $ADD
-----------------------------------------------------------------
Permanent Address
Door No/Lane/Town : $NADD
City : $NADDC
State : $NADDS
-----------------------------------------------------------------
$files
";
$config = array(
'protocol' => 'smtp',
'smpt_host' => 'mail.maseducationuae.com',
'smpt_port' => '465',
'smpt_user' => '',
'smpt_pass' => '',
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => 'TRUE'
);
$this->load->library('email', $config);
$this->email->set_newline("/r/n");
$this->email->from('Web Application Form');
$this->email->to('info#maseducationuae.com');
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
}
The problem lies within the uploadPath() function. In that function the for loop is running for the $_FILES['files'] array, but the function returns on the first iteration with the first file here,
...
// Upload file to server
if (!$this->upload->do_upload('file')){
return false;
}
else {
$file=array($_FILES['files']['name'][$i]);
return $file;
}
To get all the files, initialize an array $myFiles before the for loop, then populate the array instead of returning from the for loop and finally return the array from outside the for loop.
public function uploadpath() {
$this->load->library('upload');
// initialize empty array
$myFiles = [];
// If files are selected to upload
if (!empty($_FILES['files']['name']) && count(array_filter($_FILES['files']['name'])) > 0) {
$filesCount = count($_FILES['files']['name']);
for ($i = 0; $i < $filesCount; $i++) {
// ...
// ...
// Upload file to server
if (!$this->upload->do_upload('file')){
// do not append in $myFiles array here.
} else {
// append in $myFiles array here.
$file=array($_FILES['files']['name'][$i]);
$myFiles[] = $file;
}
}
}
return $myFiles;
}
Now you should have an array of files in here,
$files = $this->uploadpath();

Batch image upload in codeigniter

I am new to Codeigniter and i am trying to update multiple images using loop. But i am unable to do so because the foreach loop updates only 1 record if there are 3 records. Thanks in advance.
Controller.php
if(!empty($_FILES['product_image']['name'][0])) {
$number_of_files = sizeof($_FILES['product_image']['tmp_name']);
$files = $_FILES['product_image'];
$config = array(
'upload_path' => FCPATH.'uploads/product_images/',
'allowed_types' => 'jpg|png|jpeg'
);
for($i=0;$i<$number_of_files;$i++) {
$_FILES['product_image']['name'] = $files['name'][$i];
$_FILES['product_image']['type'] = $files['type'][$i];
$_FILES['product_image']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['product_image']['error'] = $files['error'][$i];
$_FILES['product_image']['size'] = $files['size'][$i];
$this->upload->initialize($config);
if($this->upload->do_upload('product_image')) {
$imgData = $this->upload->data();
}
$img[] = array(
'Image' => $files['name'][$i],
'SortOrder' => $_POST['sort_order'][$i]
);
//unlink("uploads/product_images/".$_POST['path']);
}
if($query = $this->M_Product->editProductImg($img,$prodId)) {
//$error = 0;
print_r($query);
} else {
//$error = 1;
}
}
Model.php
public function editProductImg($img,$prodId) {
$checkExist = $this->fetchSingleImage($prodId);
if(empty($checkExist)) {
if($this->db->insert_batch('tbl_product_images',$img)) {
return true;
} else {
return false;
}
} else {
foreach($img as $key => $value) {
$this->db->query("update tbl_product_images SET Image='".$value['Image']."',SortOrder='".$value['SortOrder']."' WHERE ProductId='".$prodId."'");
return $this->db->last_query();
}
}
}
Please check if number of files calculated are correct or try using
$number_of_files= count($_FILES);
Also change your first ' if ' to
if(!empty($_FILES))

Can i put a data into a table in 'Codeigniter', but the data is a 'function()'?

I have successfully done 'echo' in this 'function()', and the result went out....
The problem is, when I try to put it into a table in the database, only Photos are successful, but other data does not go into the table
in Controller Home.php
public function insert_data()
{
$config['upload_path'] = 'users/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['overwrite'] = TRUE;
$data_img_post = array();
if ( isset($_FILES['images-post']) ) {
$IMAGE = $_FILES['images-post'];
$COUNT_IMAGE = count($IMAGE['name']);
for ($i=0; $i < $COUNT_IMAGE; $i++) {
$_FILES['images-post']['name'] = $IMAGE['name'][$i];
$_FILES['images-post']['type'] = $IMAGE['type'][$i];
$_FILES['images-post']['tmp_name'] = $IMAGE['tmp_name'][$i];
$_FILES['images-post']['error'] = $IMAGE['error'][$i];
$_FILES['images-post']['size'] = $IMAGE['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('images-post');
$data_img_post[] = $this->upload->data();
}
}
$data_post = array(
'dbi_post_user_name' => $info->dbi_user_name,
'dbi_post_username' => $info->dbi_username,
'dbi_post_user_gender' => $info->dbi_user_gender,
'dbi_post_content' => $this->input->post('content-post'),
'dbi_post_tags' => $this->input->post('tags'),
'dbi_post_select_privacy' => $this->input->post('privacy-select'),
'dbi_post_dir_image' => $this->get_file_name($data_img_post)
);
$this->users_model->insert_data_post($data_post);
}
private function get_file_name($data_img_post){
$COUNT_DATA_IMG = count($data_img_post);
for ($i=0; $i < $COUNT_DATA_IMG; $i++) {
echo $data_img_post[$i]['file_name'].' ';
}
}
in Ajax XHR.js
$('#form-create-post').submit(function(ev){
ev.preventDefault();
$.ajax({
url : "home",
type : "post",
data : new FormData(this),
cache : false,
contentType : false,
processData : false,
success : function(data) {
console.log(data);
}
});
});
Please correct my mistake :D
Remove your private function() get_file_name() and TRY THIS
public function index()
{
$config['upload_path'] = 'users/'.$info->dbi_username.'./images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['overwrite'] = TRUE;
$data_img_post = array();
if ( isset($_FILES['images-post']) ) {
$IMAGE = $_FILES['images-post'];
$COUNT_IMAGE = count($IMAGE['name']);
for ($i=0; $i < $COUNT_IMAGE; $i++) {
$_FILES['images-post']['name'] = $IMAGE['name'][$i];
$_FILES['images-post']['type'] = $IMAGE['type'][$i];
$_FILES['images-post']['tmp_name'] = $IMAGE['tmp_name'][$i];
$_FILES['images-post']['error'] = $IMAGE['error'][$i];
$_FILES['images-post']['size'] = $IMAGE['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('images-post');
$data_img_post[] = $this->upload->data();
}
}
$result_array = array();
$COUNT_DATA_IMG = count($data_img_post);
for ($i=0; $i < $COUNT_DATA_IMG; $i++) {
$result_array[] = $data_img_post[$i]['file_name'].' ';
}
$array_to_string = implode(' ', $result_array);
$data_post = array(
'dbi_post_user_name' => $info->dbi_user_name,
'dbi_post_username' => $info->dbi_username,
'dbi_post_user_gender' => $info->dbi_user_gender,
'dbi_post_content' => $this->input->post('content-post'),
'dbi_post_tags' => $this->input->post('tags'),
'dbi_post_select_privacy' => $this->input->post('privacy-select'),
'dbi_post_dir_image' => $array_to_string
);
$this->users_model->insert_data_post($data_post);
}

my php code is only importing the first line of my csv file to the database

So, i have a csv file that i want to import to the database but its only importing the first line.
i dont know why its not importing all the data in my csv file.
maybe because of the line breaks?
Sample of My CSV file:
"Tiago" <20>,20,11,sip/11,20,w,2016-03-01 14:33:06,2016-03-01 14:33:09,2016-03-01 14:33:51,45
"Claudio" <10>,10,11,sip/11,20,w,2016-03-01 14:35:05,2016-03-01 14:35:07,2016-03-01 14:35:48,43
"Hortencio" <11>,11,21,sip/21,20,w,2016-03-01 14:39:55,2016-03-01 14:40:12,2016-03-01 14:40:25,30
"Andre" <19>,19,22,22000#default,s,2016-03-01 14:43:22,2016-03-01 14:43:42,2016-03-01 14:43:42,20
My model:
<?php
class Csv_model extends CI_Model {
var $gallery_path;
var $gallery_path_url;
function __construct() {
parent::__construct();
$this->gallery_path = realpath(APPPATH . '../csv');
$this->gallery_path_url = base_url() . 'csv/';
}
function do_upload($data) {
$filename = $data['fileinfo'][0];
$path = $data['fileinfo'][1];
ini_set("auto_detect_line_endings", true);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('csv_form', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('csv_success', $data);
$linecount=count(file($path.''.$filename.'.csv'));
$file = fopen($path.''.$filename.'.csv', "r");
$csv = fgetcsv($file, 0, ",", ' ');
fclose($file);
$n = 0;
echo $l=$linecount;
function validateDate($date, $format = 'Y-m-d H:i:s'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
for($i = 0; $i <= $l && $n < $l; $i++){
$insert_csv = array();
$insert_csv['clid'] = $csv[$n];
$n++;
$insert_csv['src'] = $csv[$n];
$n++;
$insert_csv['dst'] = $csv[$n];
$n++;
$insert_csv['dstchannel'] = $csv[$n];
$n++;
if(is_numeric($csv[$n])){
echo 'yes';
$insert_csv['numero'] = $csv[$n];
$n++;
}else{
echo"ok";
$insert_csv['numero'] = " ";}
if(ctype_alpha($csv[$n])){
$insert_csv['w'] = $csv[$n];
$n++;
}else{
$insert_csv['w'] = " ";
echo"ok";}
$insert_csv['start'] = $csv[$n];
$n++;
$insert_csv['answer'] = $csv[$n];
$n++;
if(validateDate($csv[$n])){
$insert_csv['end'] = $csv[$n];
$n++;
}else{
$insert_csv['end'] = " ";}
if($csv[$n] == 0){
$insert_csv['duration'] = " ";
$n++;}else{
$insert_csv['duration'] = $csv[$n];
$n++;}
$data1 = array(
'clid' => $insert_csv['clid'],
'src' => $insert_csv['src'],
'dst' => $insert_csv['dst'],
'dstchannel' => $insert_csv['dstchannel'],
'numero' => $insert_csv['numero'],
'w' => $insert_csv['w'],
'start' => $insert_csv['start'],
'answer' => $insert_csv['answer'],
'end' => $insert_csv['end'],
'duration' => $insert_csv['duration']);
$this->db->insert('chamadas', $data1);
}
echo 'Success!!!';
$success['success'] = "success";
return $success;
}
}
function get_all()
{
return $this->db->get('chamadas')->result_array();
}
}
You have to loop over each line to read the whole file, otherwise you're only reading the first line in the file
`
$file = fopen($path.''.$filename.'.csv', "r");
$csv = array();
while (($csv = fgetcsv($file, 0, ",", ' ')) !== FALSE)
{
$n[] = $csv;
}
fclose($file);
`

Cant get my app's dataTables to work. It throws an jQuery Error

Here's my application's view : http://codepad.org/hQ0qk2jZ
Here's my application's controller :
class users extends CI_Controller
{
public function __construct()
{
parent::__construct();
if( ! $this->session->userdata("uid"))
return redirect("login");
$this->load->model("admin/user_model", "user");
$this->load->helper("form");
}
public function index()
{
$this->load->helper('url');
$this->load->view('admin/users/main');
}
public function ajax_list()
{
$list = $this->user->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $user) {
$no++;
$row = array();
$row[] = $user->firstName;
$row[] = $user->lastName;
$row[] = $user->gender;
$row[] = $user->address;
$row[] = $user->dob;
if($user->photo)
$row[] = '<img src="'.base_url('upload/'.$user->photo).'" class="img-responsive" />';
else
$row[] = '(No photo)';
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_user('."'".$user->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_user('."'".$user->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->user->count_all(),
"recordsFiltered" => $this->user->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->user->get_by_id($id);
$data->dob = ($data->dob == '0000-00-00') ? '' : $data->dob; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
if(!empty($_FILES['photo']['name']))
{
$upload = $this->_do_upload();
$data['photo'] = $upload;
}
$insert = $this->user->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
if($this->input->post('remove_photo')) // if remove photo checked
{
if(file_exists('upload/'.$this->input->post('remove_photo')) && $this->input->post('remove_photo'))
unlink('upload/'.$this->input->post('remove_photo'));
$data['photo'] = '';
}
if(!empty($_FILES['photo']['name']))
{
$upload = $this->_do_upload();
//delete file
$user = $this->user->get_by_id($this->input->post('id'));
if(file_exists('upload/'.$user->photo) && $user->photo)
unlink('upload/'.$user->photo);
$data['photo'] = $upload;
}
$this->user->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
//delete file
$user = $this->user->get_by_id($id);
if(file_exists('upload/'.$user->photo) && $user->photo)
unlink('upload/'.$user->photo);
$this->user->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
private function _do_upload()
{
$config['upload_path'] = 'upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100; //set max size allowed in Kilobyte
$config['max_width'] = 1000; // set max width image allowed
$config['max_height'] = 1000; // set max height allowed
$config['file_name'] = round(microtime(true) * 1000); //just milisecond timestamp fot unique name
$this->load->library('upload', $config);
if(!$this->upload->do_upload('photo')) //upload and validate
{
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('',''); //show ajax error
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
return $this->upload->data('file_name');
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('firstName') == '')
{
$data['inputerror'][] = 'firstName';
$data['error_string'][] = 'First name is required';
$data['status'] = FALSE;
}
if($this->input->post('lastName') == '')
{
$data['inputerror'][] = 'lastName';
$data['error_string'][] = 'Last name is required';
$data['status'] = FALSE;
}
if($this->input->post('dob') == '')
{
$data['inputerror'][] = 'dob';
$data['error_string'][] = 'Date of Birth is required';
$data['status'] = FALSE;
}
if($this->input->post('gender') == '')
{
$data['inputerror'][] = 'gender';
$data['error_string'][] = 'Please select gender';
$data['status'] = FALSE;
}
if($this->input->post('address') == '')
{
$data['inputerror'][] = 'address';
$data['error_string'][] = 'Addess is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
Here's the output Output
jQuery Library is being called from only one place.
dataTables Library is being called.
I still cant get this thing to work.
TLDR - You're missing a script
You're loading dataTables.bootstrap.js which is the styling library for Bootstrap:
DataTables and its extensions can all be styled by various styling
frameworks to ensure that your tables fit seamlessly into your site /
app
~ https://datatables.net/download/index
But you're missing the Core Datatables library (jquery.dataTables.js). Check the link above for the files you need.

Categories