How to get/view images dynamically in homepage using CodeIgniter? - codeigniter

image
New_model
=========
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class New_model extends CI_Model
{
private $_table = "news";
public $title;
public $date;
public $description;
public $image = "default.jpg";
public $url;
public function rules()
{
return [
['field' => 'title',
'label' => 'Title',
'rules' => 'required'],
['field' => 'date',
'label' => 'Date',],
// 'rules' => 'required'],
['field' => 'description',
'label' => 'Description',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["new_id" => $id])->row();
}
public function save()
{
$post = $this->input->post();
// $this->new_id = uniqid();
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
$this->image = $this->_uploadImage();
$this->db->insert($this->_table, $this);
// $this->url = base_url() . 'uploads/';
$post['url'] = base_url() . 'uploads/';
}
public function update()
{
$post = $this->input->post();
$this->new_id = $post["id"];
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
if (!empty($_FILES["image"]["name"])) {
$this->image = $this->_uploadImage();
} else {
$this->image = $post["old_image"];
}
$this->db->update($this->_table, $this, array('new_id' => $post['id']));
}
public function delete($id)
{
$this->_deleteImage($id);
return $this->db->delete($this->_table, array("new_id" => $id));
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['file_name'] = $this->new_id;
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
return $this->upload->data("file_name");
}
return "default.jpg";
}
private function _deleteImage($id)
{
$new = $this->getById($id);
if ($new->image != "default.jpg") {
$filename = explode(".", $new->image)[0];
return array_map('unlink', glob(FCPATH."uploads/$filename.*"));
}
}
}
public function single($id)
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$data['news1'] = $this->New_model->limit(5)->order_by('id','desc')->get_all();
$this->current = 'news';
$this->load->view(['current' => $this->current]);
$this->load->view('news',$data);
}
Controller
==========
public function index()
{
$data["news"] = $this->New_model->getAll();
$this->load->view('index',$data);
}
public function latestnews()
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$this->load->view('news',$data);
}
view
====
<?php
if (isset($news) and $news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<img src="<?php echo $new->url . $new->image;?>" alt="image" />
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo $new->date;?></h2>
</div>
<?php
}
}
?>
I'm trying to upload an image in the dashboard with a title and date along with the image upload.
How to display that image on the homepage?
How to set the URL in the New_model?
How to set the links to display the images in the homepage?
How to set the date links?
The title field can be viewed in the homepage, but no image and dateā€¦

Try this code.
Controller: (Edited)
function index() {
$this->data["news"] = $this->new_model->getAll();
$this->load->view('index', $this->data);
}
function single_news($id) {
$this->data['news_data'] = $this->new_model->getNewsByID($id);
$this->load->view('single-news', $this->data); // Create New View file named single-news.php
}
function add_news() {
$image_status = FALSE;
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == TRUE) {
$image_name = NULL;
if ($_FILES['image']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if( ! $this->upload->do_upload('image')){
$this->data['error'] = $this->upload->display_errors();
}
$image_name = $this->upload->file_name;
$image_status = TRUE;
}
$data = array(
'title' => $this->input->post('title'),
'date' => $this->input->post('date')?date('Y-m-d', strtotime($this->input->post('date'))):NULL,
'description' => $this->input->post('description'),
'image' => $image_name
);
}
if($this->form_validation->run() == TRUE && $image_status && $this->new_model->addNews($data)) {
$this->session->set_flashdata('message', 'News has been created successfully.');
redirect('index');
} else {
$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
$this->data['page_title'] = 'Add News';
$this->load->view('add_news', $this->data);
}
}
When adding new News you don't need to add the uploaded location (Not necessary).
Model: (Edited)
function getAll() {
$q = $this->db->get('news');
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
function getNewsByID($id) {
$this->db->where('id', $id);
$q = $this->db->get('news');
if($q->num_rows() > 0) {
return $q->row();
}
return false;
}
function addNews($data) {
if($this->db->insert('news', $data)){
return true;
}
return false;
}
View: (Edited)
<?php
if ($news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<a href="<?php echo base_url('single_news/'.$new->id); ?>"
<img src="<?php echo site_url('uploads/'.$new->image); ?>" alt="image" />
</a>
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo !is_null($new->date)?date('d.m.Y', strtotime($new->date)):' - ';?></h2>
</div>
<?php
}
}
?>
single-news.php: (View)
...
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
...

Related

uploading multiple image in codeigniter using same input

views
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
</form>
controller
public function image()
{
$data['error'] = '';
$this->load->model('StackM');
if(isset($_POST['submit']))
{
$data['update_pass_error_msg'] = $this->StackM->add_multiple_image();
}
$this->load->view('stack_view');
}
Model
public function add_multiple_image(){
if((!empty($_FILES['f2']['name'])))
{
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['f2']['name'][0] == '' )
{
# code...
return "Select a file to upload";
}
else
{
$mum_files = count($files['f2']);
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['f2']['name'][$i]) )
{
$config['file_name'] = time().'-'.$files['f2']['name'][$i];
$this->load->library('upload', $config);
$_FILES['f2']['name']= $files['f2']['name']["$i"];
$_FILES['f2']['type']= $files['f2']['type']["$i"];
$_FILES['f2']['tmp_name']= $files['f2']['tmp_name']["$i"];
$_FILES['f2']['error']= $files['f2']['error']["$i"];
$_FILES['f2']['size']= $files['f2']['size']["$i"];
$filename = rand().'-'.$_FILES['f2']['name'];
if (!empty($this->upload->do_upload('f2')))
{
$dataInfo[] = $this->upload->data();
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
}
}
}
}
}
else{
$all_imgs = "";
}
}
}
else{
$all_imgs = $this->session->userdata('image');
}
$this->db->insert('table_name', $all_imgs);
The problem I am facing in this code is Think suppose if I am adding 7 images, but it's showing only 5 images in database it's not taking more then five and also I want to know while editing the form if I don't want to change the image then it should remain same image so i have stored the old image in session and checking if it is empty then only it should session variable .
But In my code if I will not upload new one If I keep old image as then it will save blank
To avoid the offset error, inside of for loop you need to check if that array index is set or not:
Here I have a demo code to upload multiple files in CodeIgniter:
views/stack_view.php
<?php if ($this->session->flashdata('status')) { ?>
<h5><?=$this->session->flashdata('status')?>: <?=$this->session->flashdata('message')?></h5>
<?php } ?>
<?=form_open_multipart('stack', array('id' => 'my_id'))?>
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
<?=form_close()?>
controllers/Stack.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Stack extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
}
public function index()
{
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['userfile']['name'][0] == '' ) {
# code...
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "Select a file to upload");
}
else
{
$mum_files = count($files['userfile']);
$dataInfo = array();
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['userfile']['name'][$i]) ) {
$config['file_name'] = time().'-'.$files['userfile']['name'][$i];
$this->load->library('upload', $config);
$_FILES['userfile']['name']= $files['userfile']['name']["$i"];
$_FILES['userfile']['type']= $files['userfile']['type']["$i"];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name']["$i"];
$_FILES['userfile']['error']= $files['userfile']['error']["$i"];
$_FILES['userfile']['size']= $files['userfile']['size']["$i"];
$filename = rand().'-'.$_FILES['userfile']['name'];
if ( ! $this->upload->do_upload('userfile'))
{
$error_message = $this->upload->display_errors();
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "$error_message");
}
else
{
//$data = array('upload_data' => $this->upload->data());
$this->session->set_flashdata('status', 'success');
$this->session->set_flashdata('message', "Files upload is success");
}
$dataInfo[] = $this->upload->data(); //all the info about the uploaded files are stored in this array
}
}
//here you can insert all the info about uploaded file into database using $dataInfo
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$insert_data = array(
'your_column_name' => rtrim($all_imgs,",")
);
$this->db->insert('your_table_name', $insert_data);
}
}
$this->load->view('stack_view');
}
}
Try this script and I hope you will get some help from this.
This is working script try to upload it
public function upload()
{
$this->load->library('session');
if ( ! empty($_FILES))
{
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 5120; //limit only 5 Mb
$this->load->library('upload');
$files = $_FILES;;
$number_of_files = count($_FILES['files']['name']);
$errors = 0;
$myname = $this->input->post('ad_title');
for ($i = 0; $i < $number_of_files; $i++)
{
//$randVal = rand(450,4550).time('d-y-m');
$filename = basename($files['files']['name'][$i]);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename.''.time('d-y-m')).'.'.$extension;
$_FILES['files']['name'] = $new; //$files['files']['name'][$i];
$_FILES['files']['type'] = $files['files']['type'][$i];
$_FILES['files']['tmp_name'] = $files['files']['tmp_name'][$i];
$_FILES['files']['error'] = $files['files']['error'][$i];
$_FILES['files']['size'] = $files['files']['size'][$i];
$image = array('upload_data' => $this->upload->data());
$image_name = $_FILES['files']['name'];
$ip = $this->input->ip_address();
$this->session->set_userdata("userIP",$ip);
//$this->session->unset_userdata("userIP");
$Dval = array(
"filename" => $image_name,
"ip" => $this->input->ip_address()
);
$this->member_model->tmp_image($Dval);
$this->upload->initialize($config);
if ( $this->upload->do_upload("files"))
{
$errors++;
$data = $this->upload->data();
echo json_encode($data['file_name']);
//code is for thumbnail and watermark on images
//$this->watermark($data['full_path']);
//$myPathfT = $config1['upload_path'] = "./assets/thumbs/".$aDir;
//mkdir($myPathfT);b
$config1 = array();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'assets/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['quality'] = 50;
$config1['height'] = 150;
$config1['width'] = 150;
$this->load->library('image_lib',$config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
if ($errors > 0)
{
//echo "Data Transferred";
}
}
elseif ($this->input->post('file_to_remove'))
{
$aDir = $this->session->userdata('Dir');
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/mainFilesData/$aDir/" . $file_to_remove);
$array = $this->session->userdata('photo');
$dataF = array_diff($array, array($file_to_remove));
$this->session->set_userdata('photo',$dataF);
}
else
{
$this->listFiles();
}
}

Stop form validation submitting if error on file upload

Question: When the user has filled in the form validation correct but there is a error on image upload how is it possible to stop the form being submitted
Currently still submits data even if there is a error on my image upload.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
return true;
}
}
$this->user_model->insert($this->upload->data());
}
if ($this->upload->display_errors() != false) {
$this->error['warning'] = $this->upload->display_errors();
}
if (validation_errors() != false) {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
}
Model
<?php
class User_model extends CI_Model {
public function insert($upload_data = array()) {
$this->db->trans_begin();
$options = [
'cost' => 12,
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'user_group_id' => $this->input->post('user_group_id'),
'username' => $this->input->post('username'),
'password' => $hash,
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'image' => ($upload_data['file_name']) ? $upload_data['file_name'] : '',
'country' => $this->input->post('country'),
'timezone' => $this->input->post('timezone'),
'status' => $this->input->post('status'),
'date_added' => date('Y-m-d')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'user');
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
} else {
$this->db->trans_commit();
}
}
}
Codeigniter Version 3.1.0 & XAMPP Windows 10
Have solved it now.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'username', 'trim|required|is_unique[user.username]');
$this->form_validation->set_message('is_unique', 'Opps looks like someone has all ready got that {field}');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if ($this->upload() == true) {
$this->user_model->insert($this->upload->data());
}
} else {
$this->user_model->insert();
}
}
if (validation_errors() != '') {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
public function upload() {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$this->error['warning'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
} else {
return true;
}
return !$this->error;
}
}

How can i display error messages in CodeIgniter

Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$this->year_model->insert($_POST);
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
Model:
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
}
View:
<div class="text-danger">
//display error message
</div>
MY Question: How can i display model error message in view............................................................
use below updated code for your solution
Model :
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
return TRUE;
}
add_year
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$ret = $this->year_model->insert($_POST);
if(!$ret){
$this->session->set_flashdata('error_view',$ret);
}
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
in view
<?php
echo $this->session->flashdata('error_view');
?>
Use this Code
Note : please set your table and field name in is_unique function !
Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id))
{
$this->form_validation->set_rules('year_name', 'Year Name', 'required|is_unique[table_name.field_name]');
if ($this->form_validation->run() == FALSE) {
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else {
if( $this->year_model->insert($_POST)==true)
{
redirect('admin/Year');
}
}
} else
{
redirect('admin/Login');
}
}
Model
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
return true;
} else {
return false;
}
}
View File
<div class="panel-body">
<?php if(validation_errors()) { ?>
<div class="alert alert-danger"><?php echo validation_errors(); ?></div>
<?php } ?>

When echo multiple file data it only display last file info

On my multiple upload library I have a function which is called upload data.
And another function called upload.
For some reason when I select multiple images and is success full when I use on my controller
$data = $this->multiple_upload->upload_data();
echo $data['file_name'];
It will only get the name of the last file selected it does not return all file names selected. It should display all file names selected.
Question: How on my library function upload_data() can I make sure can return data correctly rather than just the last one. the upload_data function just seems to only return the last file information.
Library
<?php
class Multiple_upload {
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
$check_error = 0;
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$this->file_temp = $this->files[$field]['tmp_name'][$key];
$this->file_size = $this->files[$field]['size'][$key];
$this->get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($this->get_file_extension));
if (!in_array($this->get_file_extension_end, $this->allowed_types)) {
$this->set_error('file_extension_not_allowed');
$check_error++;
}
if ($this->files[$field]['size'][$key] > $this->max_size) {
$this->set_error('file_size_check');
$check_error++;
}
if ( ! #copy($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
if ( ! #move_uploaded_file($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
$this->set_error('upload_destination_error', 'error');
$check_error++;
}
}
}
if($check_error > 0 ) {
return FALSE;
}
// This lets me get file data in another function
return $this;
}
}
public function upload_data() {
$data = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
public function set_error($message) {
$this->CI->lang->load('upload', 'english');
$msg = "";
if ($message == 'upload_path_not_set') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'upload_path_in_correct') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'file_extension_not_allowed') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->get_file_extension_end);
}
if ($message == 'file_size_check') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->max_size);
}
return $this->error_message[] = $msg;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
$message = "";
if (isset($this->error_message)) {
foreach($this->error_message as $msg) {
$message .= $open_tag . $msg . $close_tag;
}
}
return $message;
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
I have tried
public function upload_data() {
$data[] = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
Controller index function
public function index(){
$data['error'] = '';
$this->load->library('multiple_upload');
$config['upload_path'] = 'uploads';
$config['allowed_types'] = array('jpg', 'png');
$config['max_size'] = 3000000;
//$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
$this->multiple_upload->set_config($config);
if ($this->multiple_upload->upload() == FALSE) {
$data['error'] = $this->multiple_upload->display_error_messages('<div class="alert alert-danger">', '</div>');
$this->load->view('upload', $data);
} else {
$data = $this->multiple_upload->upload_data();
echo $data['file_name'];
}
}
<?php
class Multiple_upload {
private $filenames;
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
$this->filenames = array();
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
$check_error = 0;
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$this->filenames[] = $this->files[$field]['name'][$key];
$this->file_temp = $this->files[$field]['tmp_name'][$key];
$this->file_size = $this->files[$field]['size'][$key];
$this->get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($this->get_file_extension));
if (!in_array($this->get_file_extension_end, $this->allowed_types)) {
$this->set_error('file_extension_not_allowed');
$check_error++;
}
if ($this->files[$field]['size'][$key] > $this->max_size) {
$this->set_error('file_size_check');
$check_error++;
}
if ( ! #copy($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
if ( ! #move_uploaded_file($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
$this->set_error('upload_destination_error', 'error');
$check_error++;
}
}
}
if($check_error > 0 ) {
return FALSE;
}
// This lets me get file data in another function
return $this;
}
}
public function upload_data()
{
$data = array();
foreach($this->filenames as $filename)
{
$data[] = array(
'file_name' => $filename,
'file_path' => FCPATH . $this->upload_path . '/'
);
}
return $data;
}
public function set_error($message) {
$this->CI->lang->load('upload', 'english');
$msg = "";
if ($message == 'upload_path_not_set') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'upload_path_in_correct') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'file_extension_not_allowed') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->get_file_extension_end);
}
if ($message == 'file_size_check') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->max_size);
}
return $this->error_message[] = $msg;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
$message = "";
if (isset($this->error_message)) {
foreach($this->error_message as $msg) {
$message .= $open_tag . $msg . $close_tag;
}
}
return $message;
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
And
public function index()
{
$data['error'] = '';
$this->load->library('multiple_upload');
$config['upload_path'] = 'uploads';
$config['allowed_types'] = array('jpg', 'png');
$config['max_size'] = 3000000;
//$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
$this->multiple_upload->set_config($config);
if ($this->multiple_upload->upload() == FALSE)
{
$data['error'] = $this->multiple_upload->display_error_messages('<div class="alert alert-danger">', '</div>');
$this->load->view('upload', $data);
}
else
{
$data = $this->multiple_upload->upload_data();
foreach($data as $file)
{
echo $file['file_name']."<br>";
}
}
}
you can use array to save all files information in upload_data function.
public function upload_data() {
$data = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
to
public function upload_data() {
$data[] = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
it will return array of all the file details

Dynamic Select Dropdowns with CodeIgniter

I'm using CodeIgniter to develop a web application and wondered if anyone could help with a problem that has arose.
I have two dropdowns - Division and Teams. I'm creating a fixture so want to be able to allow the user to choose a division from the first dropdown, then within the second dropdown will only contain the teams from the selected division.
The Code I have so far:
Controller:
function create() {
$data['division_list'] = $this->add_fixture_model->get_divisions();
$data['team_list'] = $this->add_fixture_model->get_teams();
$data['referee_list'] = $this->add_fixture_model->get_referee();
// field name, error message, validation rules
$this->form_validation->set_rules('team_name', 'Team Name', 'trim|required');
$this->form_validation->set_rules('home_team', 'Home Team Name', 'trim|required');
$this->form_validation->set_rules('away_team', 'Away Team Name', 'required');
$this->form_validation->set_rules('division_name', 'Division', 'trim|required');
$this->form_validation->set_rules('referee', 'Referee', 'trim|required');
$this->form_validation->set_rules('fixture_week', 'Fixture Week', 'trim|required');
$this->form_validation->set_rules('fixture_day', 'Fixture Day', 'trim|required');
$this->form_validation->set_rules('fixture_month', 'Fixture Month', 'trim|required');
$this->form_validation->set_rules('fixture_year', 'Fixture Year', 'trim|required');
$this->form_validation->set_rules('confirm_day', 'Fixture Confirm Day', 'trim|required');
$this->form_validation->set_rules('confirm_month', 'Fixture Confirm Month', 'trim|required');
$this->form_validation->set_rules('confirm_year', 'Fixture Confirm Year', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('includes/top');
$this->load->view('includes/header');
$this->load->view('league/add_fixture', $data);
$this->load->view('includes/footer');
}
else
{
if($query = $this->add_fixture_model->add_fixture())
{
$this->load->view('includes/top');
$this->load->view('includes/header');
$this->load->view('league/fixture_added');
$this->load->view('includes/footer');
}
else
{
$this->load->view('includes/top');
$this->load->view('includes/header');
$this->load->view('league/fixture_added', $data);
$this->load->view('includes/footer');
}
}
}
Model:
class Add_fixture_model extends Model {
function add_fixture()
{
$add_new_fixture = array(
'team_name' => $this->input->post('team_name'),
'home_team' => $this->input->post('home_team'),
'away_team' => $this->input->post('away_team'),
'division' => $this->input->post('division_name'),
'ground' => $this->input->post('ground'),
'ground_postcode' => $this->input->post('ground_postcode'),
'referee' => $this->input->post('referee'),
'fixture_week' => $this->input->post('fixture_week'),
'fixture_day' => $this->input->post('fixture_day'),
'fixture_month' => $this->input->post('fixture_month'),
'fixture_year' => $this->input->post('fixture_year'),
'confirm_day' => $this->input->post('confirm_day'),
'confirm_month' => $this->input->post('confirm_month'),
'confirm_year' => $this->input->post('confirm_year')
);
$insert = $this->db->insert('fixtures', $add_new_fixture);
return $insert;
}
function get_divisions()
{
$this->db->from('divisions');
$this->db->order_by('division_name');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[''] = 'Select a division';
$return[$row['id']] = $row['division_name'];
}
}
return $return;
}
function get_teams()
{
$this->db->from('teams');
$this->db->order_by('team_name');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[''] = 'Select a team';
$return[$row['id']] = $row['team_name'];
}
}
return $return;
}
function list_teams() {
$this->db->from('teams');
$this->db->where('division_id', $this->input->post('id'));
$this->db->order_by('team_name');
$result = $this->db->get();
return $result;
}
function get_referee() {
$this->db->from('referees');
$this->db->order_by('id');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[''] = 'Select a referee';
$return[$row['id']] = $row['first_name'].' '.$row['surname'];
}
}
return $return;
}
}
View:
<?php echo form_open('add_fixture/create') ;?>
<label for="division" class="label">Division:</label><?php $js = 'id="division"'; echo form_dropdown('division', $division_list, set_value('division'), $js); ?>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('select#division').change(function() {
var div = $(this).val();
if(div != '') {
$.post("/add_fixture/list_teams/",{division_id: div}, function(data){
$("select#team_name").html(data);
});
}
});
});
</script>
Any help would very much be appreciated :)

Resources