Codeigniter: How to upload files path to database? - php

I am trying to put the file path to database, I already uploaded the file but I don't know how to get the path of the file to put it in the database?
Here is the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class dogo extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('insert_article');
}
public function index()
{
$this->load->view('dogo/dashboard.php');
}
//add new post to database including uploading image
public function new_post()
{
//used for the dropdown menu (category)
$this->load->model('dogo_cat');
$data['categores_dropdown'] = $this->dogo_cat->get_categories();
//form validation
$this->load->library('form_validation');//load the validation library
$this->form_validation->set_rules('title', 'title of the post', 'required');
$this->form_validation->set_rules('text', 'text of the post', 'required');
//$this->form_validation->set_rules('image', 'image of the post', 'required');
$this->form_validation->set_rules('category', 'category of the post', 'required');
//the form validation condition
if($this->form_validation->run() == FALSE){
//error
//$this->view_data
$this->load->view('dogo/new_post.php', $data);
}else{
//no error in the form
$title = $this->input->post('title');
$text = $this->input->post('text');
$category = $this->input->post('category');
$publish = $this->input->post('publish');
//$img_nw = $this->input->post('img_nw');
//$img_nw = $this->input->post('img_nw');
$image_file = $this->input->post('image_file');
//uploading
$this->load->model('upload_new_post');
if($this->input->post('upload')){
$this->upload_new_post->do_upload();
//$this->insert_article->insert_new_post($title, $category, $img_nw, $text, $source, $publish);
$data['images'] = $this->upload_new_post->get_images();
echo "title of the post: " . $title . "<br /> and the text of the post " . $text . "<br /> and category is: " . $category . "<br /> and publish is: " .$publish . "<br /> and image: <pre>" . $do_upload ."</pre>";
//echo $img_nw;
$this->load->view('dogo/new_post.php', $data);
}
}
}
}
And here is the model to upload it:
<?php
class upload_new_post extends CI_Model{
// retreive categories
var $file_path;
var $file_path_url;
function __construct() {
parent::__construct();
$this->file_path = realpath(APPPATH . '../post_data/images');
$this->file_path_url = base_url().'post_data/images/';
}
function do_upload(){
$config=array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->file_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->file_path . '/thumbs',
'maintain_ration' => true,
'width' => 150,
'height' => 150
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
function get_images(){
$files = scandir($this->file_path);
$files = array_diff($files, array('.', '..', 'thumbs'));
$images = array();
foreach ($files as $file){
$images [] = array(
'url' => $this->file_path_url . $file,
'thumb_url' => $this->file_path_url . 'thumbs/' .$file
);
}
return $images;
}
}
And here the model to insert query:
<?php
class Insert_article extends CI_Model{
//insert new post
function __construct() {
parent::__construct();
}
function insert_new_post($title, $category, $img_nw, $text, $source, $publish)
{
$query_insert = "INSERT INTO hs_news_nw (idcat_nw, idsc_nw, idusr_nw, title_nw, img_nw, text_nw, active_nw, totalview_nw, date_nw) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$this->db->query($query_insert, array($category, $source, 1, $title, $img_nw, $text, 1, 1000, '2011-10-12 02:01:24'));
}
}

You should return $image_data from do_upload() function in your upload_new_post model.
$image_data = $this->upload->data();
..
..
return $image_data;
$image_data contains all the info about uploaded file including file name and path (do a print_r). Then you can pass it onto Insert_article model from your controller to store in database.
For reference:
http://codeigniter.com/user_guide/libraries/file_uploading.html

Please try if $fpath gives you the correct path:
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$image_data = $this->upload->data();
$fname=$image_data[file_name];
$fpath=$image_data[file_path].$fname;

you can use realpath to get real file location if I correctly understood you

You can try to upload by File Processing Library..
Controller :
public function add_slide() {
// set the page name
$data['title_admin'] = "Add & View Slide Information";
// load the custom file processing library
$this->load->library('file_processing');
$this->load->library('form_validation');
// check if click on the submit button
if ($this->input->post('Save')) {
// write the validation rule
$this->form_validation->set_rules('slide_name', 'Name', 'required');
$this->form_validation->set_rules('slide_short_description', 'Short Description', '');
$this->form_validation->set_rules('slide_long_description', 'Detail Description', '');
$this->form_validation->set_rules('slide_image', 'Image', 'callback_file_validate[no.slide_image.jpg,gif,png]');
//$this->form_validation->set_rules('slide_mission_vision', 'Diabetes Profile', 'callback_file_validate[no.slide_mission_vision.pdf]');
// check the validation
if ($this->form_validation->run()) {
$addData['slide_name'] = $this->input->post('slide_name');
$addData['slide_short_description'] = $this->input->post('slide_short_description');
$addData['slide_long_description'] = $this->input->post('slide_long_description');
$addData['slide_image'] = $this->file_processing->image_upload('slide_image', './images/slide/', 'size[500,1000|100,500]');
//$addData['slide_mission_vision'] = $this->file_processing->file_upload('slide_mission_vision', './images/slide_mission_vision/', 'pdf');
$addData['slide_add_date'] = date('Y-m-d');
// call the crate model and inset into database
if ($this->sa_model->save_slide_info($addData)) {
$this->session->set_flashdata('success_msg', 'Save Information Successfully!!');
redirect('super_admin/add_slide');
}
else
$data['error_msg'] = mysql_error();
}
}
// load the views
$data['s2'] = TRUE;
$data['slide_info'] = $this->sa_model->select_all_slide_info();
$data['admin_main_content'] = $this->load->view('admin/add_slide', $data, true);
$this->load->view('admin/admin_master', $data);
}
// file validation
public function file_slide_validate($fieldValue, $params) {
// get the parameter as variable
list($require, $fieldName, $type) = explode('.', $params);
// get the file field name
$filename = $_FILES[$fieldName]['name'];
if ($filename == '' && $require == 'yes') {
$this->form_validation->set_message('file_validate', 'The %s field is required');
return FALSE;
} elseif ($type != '' && $filename != '') {
// get the extention
$ext = strtolower(substr(strrchr($filename, '.'), 1));
// get the type as array
$types = explode(',', $type);
if (!in_array($ext, $types)) {
$this->form_validation->set_message('file_validate', 'The %s field must be ' . implode(' OR ', $types) . ' !!');
return FALSE;
}
}
else
return TRUE;
}
Model :
// insert new record into user table
public function save_slide_info($data) {
$this->db->insert('tbl_slide', $data);
return $this->db->affected_rows();
}

Related

I want stored image delete when Updated with new image

I am new to codeigniter and I am having problem in edit item image, not that it don't get update as it do but there are too many images in the upload folder directory.
What I want to do is I want the previously stored image to be deleted in the upload directory when I update new image.
Here is my controller:
function edit($shop_id = null){
if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
/* Breadcrumbs */
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
$this->data['shop_id'] = $shop_id;
/* Get all category */
$this->data['shopInfo'] = $this->shop_model->getShopInfo($shop_id);
//echo "<pre>";print_r( $this->data['shopInfo']);echo "</pre>";exit;
/* Validate form input */
$this->form_validation->set_rules('shop_name', 'Shop Name', 'trim|required');
$this->form_validation->set_rules('shop_latidude', 'Shop Latidude', 'trim|required');
$this->form_validation->set_rules('shop_longitude', 'Shop Longitude', 'trim|required');
if($this->form_validation->run() == true) {
$config['upload_path'] = './assets/uploads/shop/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
$img_upload = $this->upload->do_upload($img);
$data = $this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/shop/'.$file['file_name'];
if($img_upload == 1 ) $post_photo = $photo;
else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
$shopInfo = array(
'shop_name' => $this->input->post('shop_name'),
'merchant_id' => $this->input->post('merchant_id'),
'photo' => $post_photo,
'description' => $this->input->post('shop_desc'),
'registered_date'=> date('Y-m-d H:i:s'),
'is_active' => 1,
'shop_location' => $this->input->post('shop_loc'),
'shop_address' => $this->input->post('shop_add'),
'shop_phone' => $this->input->post('shop_ph'),
'shop_latitude' => $this->input->post('shop_latidude'),
'shop_longitude'=> $this->input->post('shop_longitude'),
'open_hour' => $this->input->post('open_hour'),
'close_hour' => $this->input->post('close_hour'),
'remark' => $this->input->post('remark'),
'approved' => $status
);
$this->shop_model->shopUpdate($shop_id, $shopInfo);
redirect(base_url() . 'admin/shop', 'refresh');
} else {
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->data['merchant'] = $this->merchant_model->getAllMerchants();
$this->template->admin_render("admin/shop/edit", $this->data);
}
}
Here is my Model:
function shopUpdate($shop_id, $shopInfo) {
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function shopUpdate($shop_id, $shopInfo) {
$q = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
if ($q->num_rows() > 0) {
$imgName = $q->row();
// image path must be './admin/shop'
unlink("./{image pathe}/".$imgName);
}
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
you got file name when image got uploaded so get the file name where you are going to update and delete file first. Use unlink to delete file. run update query.
you just need to change in model for updating and deleting at same time.
First, check if new image uploading or not
$new_image = $_FILES['userfile']['name'] ? $_FILES['userfile']['name'] : '';
if($new_image != ''){
$old_image = $this->shop_model->getOlgImage($shop_id);
if(isset($old_image) && file_exists('image-path/photo.jpg')){
unlink('image-path/image');
}
}
Old image is now deleted. Upload new
$config['upload_path'] = './assets/uploads/shop/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
Give name of your input type file name to $this->upload->do_upload() not variable
No need to add $this->upload->data() twice
if($this->upload->do_upload('userfile')){
$data = $this->upload->data();
$photo = base_url().'assets/uploads/shop/'.$data['file_name'];
$post_photo = $photo;
} else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
Get old image
public function getOldImage($shop_id){
return $this->db->get_where('shop', ['shop_id' => $shop_id])->row()->photo;
}
First, you need to get image name from the database by ID then update record. Once the record is updated then you can delete that image the folder directory.
function shopUpdate($shop_id, $shopInfo) {
//fetch image name from the database by shop_id
$imageName = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
//record is updated successfully now delete that image from folder
if ($imageName->num_rows() > 0) {
unlink("./{image pathe}/".$imageName->row());
}
return true;
} else {
return false;
}
} else {
return false;
}
}
unlink()

Codeigniter image upload validation with controller and function

I have a small issue on this code for the to add a product on my system I am using V_add_pro function, when the image upload part is coming I am facing some issues to validate, so that I used a different function to validate through callback, its not working. the main issue is i am saving the image name only to the database, so how to return the image name only?
public function v_add_pro(){
$this->load->model('B_menu');
$data = array('status' => false, 'msg' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules("pro_name", "name needed", "trim|required");
$this->form_validation->set_rules("pro_price", "price needed", "trim|required");
$this->form_validation->set_rules("pro_desc", "description is needed", "trim|required");
$this->form_validation->set_rules("dropzone", "select an image", "trim|required|callback_validate_image");
$this->form_validation->set_rules("pro_cat", "please select a category","callback_check_default|trim|required");
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if ($this->form_validation->run()) {
$data['status'] = true;
$pro_data = array(
'pname' => $this->input->post('pro_name'),
'pprice' => $this->input->post('pro_price'),
'pdesc' => $this->input->post('pro_desc'),
'pimage' =>$this->input->post('dropzone'),
'catid' => $this->input->post('pro_cat'),
);
$this->B_menu->add($pro_data);
} else {
foreach ($_POST as $key => $value) {
$data['msg'][$key] = form_error($key);
}
}
echo json_encode($data);
}
//to check the selected value for category
function check_default($post_string)
{
return $post_string == '0' ? FALSE : TRUE;
}
//to upload the image to the correct path
public function validate_image() {
$config = array(
'allowed_types'=>'jpg|png|gif',
'upload_path'=> realpath(APPPATH . '../skin/images'),
'max_size'=>1
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('dropzone'))
{
$this->form_validation->set_message('validate_image',$this->upload->display_errors());
} else {
$file_info = $this->upload->data();
$img = $file_info['file_name'];
return $img;
}
}
public function validate_image()
{
/* Start: Image Uploading */
$baseurl = $this->config->base_url();
$profile_photo = "";
$profile_path = '';
$config['upload_path'] = './assets/profile_pictures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
if (!empty($_FILES))
{
$this->file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$this->file_name = time() . "." . $this->file_ext;
$config['file_name'] = $this->file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image', FALSE))
{
echo $this->upload->display_errors();
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if ($_FILES['image']['error'] != 4)
{
return false;
}
}
else
{
$profile_photo = $this->file_name;
$profile_path = $baseurl . "assets/profile_pictures";
return $profile_photo;
}
}
/* End: Image Uploading */
To add-ons I am just saving file name as current timestamp thats it. Also return $imagename and also try to echo this
echo $this->upload->display_errors();

can't upload image to database in codeigniter

I have tried almost all the forums on google but can't find a solution
to this problem, i have a product upload form which have two upload
images options as well, but i can't to seem upload any image to
database, neither i can't get the upload path method working. help me
out please. what is the best possible way to upload images to db?
**Controller File**
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('admin_model');
}
public function index(){
$data['cats'] = $this->admin_model->get_cats();
$data['brands'] = $this->admin_model->get_brands();
$this->load->view('admin_view', $data, $data);
$data['upload_data'] = $this->upload->data();
$image = base_url("uploads/". $data['raw_name'] . $data['file_ext']);
$_POST['product_img1'] = $image;
//$image_url = $this->upload->data('full_path');
$product = array(
'product_name' => $this->input->post('name'),
'brand_id' => $this->input->post('brands'),
'cat_id' => $this->input->post('catagories'),
'product_price' => $this->input->post('price'),
'product_desc' => $this->input->post('desc'),
'product_img1' => $this->input->post('img')
);
//$insert_id = $this->admin_model->form_insert($product);
/**
$config = array(
'upload_path' => "./images/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => true
);
$this->load->library('upload', $config);
$data = $this->upload->data();
$image = base_url("./uploads/". $data['raw_name'] . $data['file_ext']);
$_POST['image'] = $image;
$this->load->model('admin_model');
**/
//if (!empty($_POST)) {
// Loading model
//$this->upload->do_upload();
//$data = array('product_img1' => $this->upload->data());
//$file_data = $this->upload->data();
//$data['product_img1'] = base_url().'/uploads/'.$file_data['file_name'];
//$product_img1 = $_FILES['product_img1']['name'];
//$product_img2 = $_FILES['product_img2']['name'];
//$temp_name1 = $_FILES['product_img1']['tmp_name'];
//$temp_name2 = $_FILES['product_img2']['tmp_name'];
//m_checkstatus(conn, identifier)ove_uploaded_file($temp_name1, "uploads/$product_img1");
//move_uploaded_file($temp_name2, "uploads/$product_img2");
//$this->admin_model->insert($data);
// Calling model
//$id = $this->admin_model->form_insert($data);
//}
}
}
?>
**Model File**
<?php
class admin_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($product){
// Inserting in Table(students) of Database(college)
$insert = $this->db->insert('products', $product);
return $insert;
}
function get_cats(){
$this->db->select("*");
$this->db->from("catagories");
$query = $this->db->get();
return $query->result_array();
}
function get_brands(){
$this->db->select("*");
$this->db->from("brands");
$query = $this->db->get();
return $query->result_array();
}
}
?>
This question was already answered here
$this->input->post('img') in model won't work to retrieve the image information. Because the images are stored in $_FILES not in $_POST. So you need to use the upload library in codeignitor like below.
Also, make sure that your form contains the enctype="multipart/form-data" attr and your column type is blob in the database.
i will give you an example.This is the controller section.
public function add()
{
if (empty($_FILES['image']['name']))
{$this->session->set_flashdata('yes', 'Please Upload an image');
redirect($_SERVER['HTTP_REFERER']);
}
else
{
$target_dir = "images/products/";
$target_file = $target_dir . time().basename($_FILES["image"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$imgName = time().basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],$target_file);
$this->adminmodel->addproducts($imgName);
}
}
Model section
public function addproducts($imgName)
{
$data = array(
'name' => $this->input->post('name'),
'category' => $this->input->post('category'),
'image' => $imgName
);
$this->db->insert('products', $data);
$this->session->set_flashdata('yes', 'Product added successfully');
redirect('admin/products/productlist');
}
View Section(Form)
form role="form" action="admin/products/add" method="post" enctype="multipart/form-data" id="contact-form">
Your Form should contain enctype="multipart/form-data"

how can i upload a video and it saved to a folder in codeigniter?

i'm new to codeigniter. i need help to upload a picture and video and save it to folder and database.
here is my controller
public function upload()
{
$this->m_upload->upload();
$this->upload_gambar();
}
public function upload_gambar()
{
//load the helper
$this->load->helper('form');
$config['upload_path'] = 'assets/gallery/images';
$config['allowed_types'] = 'gif|jpg|png|mp4';
$config['max_size'] = '';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->set_allowed_types('*');
$data['upload_data'] = '';
$this->upload->do_upload('uploadan');
redirect(c_upload);
}
and this is my models
public function upload()
{
$title = $this->input->post('title');
$details = $this->input->post('details');
$type = $this->input->post('gallery');
$picture = $_FILES['uploadan']['name'];
$data = array(
'url' => $picture,
'title' => $title,
'details' => $details,
'category' => $type
);
$this->db->insert('gallery', $data);
}
i've already set upload_max_filesize and post_max_size in the php.ini but it still not working. please help me fix this problem. thankyou
Try this
In Controller
$configVideo['upload_path'] = 'assets/gallery/images'; # check path is correct
$configVideo['max_size'] = '102400';
$configVideo['allowed_types'] = 'mp4'; # add video extenstion on here
$configVideo['overwrite'] = FALSE;
$configVideo['remove_spaces'] = TRUE;
$video_name = random_string('numeric', 5);
$configVideo['file_name'] = $video_name;
$this->load->library('upload', $configVideo);
$this->upload->initialize($configVideo);
if (!$this->upload->do_upload('uploadan')) # form input field attribute
{
# Upload Failed
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('controllerName/method');
}
else
{
# Upload Successfull
$url = 'assets/gallery/images'.$video_name;
$set1 = $this->Model_name->uploadData($url);
$this->session->set_flashdata('success', 'Video Has been Uploaded');
redirect('controllerName/method');
}
In Model
public function uploadData($url)
{
$title = $this->input->post('title');
$details = $this->input->post('details');
$type = $this->input->post('gallery');
$data = array(
'url' => $url,
'title' => $title,
'details' => $details,
'category' => $type
);
$this->db->insert('gallery', $data);
}
Add mimes code for media file in:
application/config/mimes.php
especially for mp4

Why is my gallery view page throwing up an error?

Im currently developing using codeigniter a gallery in an interactive profile where each user can upload their own section of images. Currently my view page is throwing up a Message: Undefined variable: images. This is despite I already have a get_images function in my model there also being an if statement in my view so it will understand not to try to display images if none have been uploaded yet. How can i fix this issue? Im also trying to store any image uploaded in a gallery database so that beside each user's name it shows any image they have uploaded. Here is my code so far:
Controller:
class Gallery extends CI_Controller {
function __construct()
{
// Call the parent construct
parent::__construct();
$this->load->model("profiles");
$this->load->model("gal_model");
$this->load->helper(array('form', 'url'));
$this->gallery_path = 'web-project-jb/assets/gallery';
$this->gallery_path_url = base_url().'web-project-jb/assets/gallery/';
}
function upload()
{
$config = array(
'allowed_types' =>'gif|jpg|jpeg|png',
'upload_path' => $this->gallery_path,
'max_size' => 10000,
'max_width' => 1024,
'max_height' => 768);
$this->load->library('upload', $config);
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data["full_path"],
'new_image' => $this->gallery_path. '/thumbs',
'maintain_ration' => true,
'width' => 150,
'height' => 100
);
$this->load->library("image_lib", $config);
$this->image_lib->resize();
$username = $this->session->userdata('username');
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$this->load->view('shared/header');
$this->load->view('gallery/galtitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('gallery/galview', $error, $viewData, array('error' => ' ' ));
$this->load->view('shared/footer');
}
else
{
$file_data = $this->upload->data();
$image = $this->gallery_path.$file_data['file_name'];
$data['image'] = $this->gallery_path.$file_data['file_name'];
$this->username = $this->session->userdata('username');
$this->gal_model->putGalleryImage($username, $image);
$this->session->set_userdata($image);
$viewData['username'] = $username;
$data['gal_model'] = $this->gal_model->get_images($username);
$username = $this->session->userdata('username');
$this->load->view('shared/header');
$this->load->view('gallery/galtitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('gallery/galview', $data, $viewData);
$this->load->view('shared/footer');
}
}
function index()
{
$username = $this->session->userdata('username');
$this->load->library('upload');
$data['profileimages'] = $this->gal_model->get_images($username);
$file_data = $this->upload->data();
$file_data['file_name'] = $this->gal_model->get_images($username);
$image = $this->gallery_path.$file_data['file_name'];
$data['image'] = $file_data['file_name'];
$viewData['username'] = $username;
$this->load->view('shared/header');
$this->load->view('gallery/galtitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('gallery/galview', $viewData, $data, array('error' => ' ' ));
$this->load->view('shared/footer');
}
}
Model:
class Gal_model extends CI_Model
{
var $gallery_path;
var $gallery_path_url;
function Gal_model()
{
parent::__construct();
$this->gallery_path = 'web-project-jb/assets/gallery';
$this->gallery_path_url = base_url().'web-project-jb/assets/gallery/';
}
function exists($username)
{
$this->db->select('*')->from("gallery")->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return true;
/*
echo "user $user exists!";
$row = $query->row();
echo " and his profileimage is $row->profileimage";
*/
}
else
{
return false;
//echo "no such user as $user!";
}
}
function putGalleryImage($username, $image)
{
$record = array('user' => $username, 'galleryimage' => $image);
$this->session->set_userdata($image);
if ($this->exists($username))
{
$this->db->where('user', $username)->update('gallery', $record);
}
else
{
$this->db->where('user', $username)->insert('gallery', $record);
}
}
function get_images($username)
{
$this->db->select('*')->from('gal_model')->where('user', $username);
$files = scandir($this->gallery_path);
$files = array_diff($files, array('.', '..', 'thumbs'));
$images = array();
foreach ($files as $file){
$images[] = array(
'url' => $this->gallery_path_url.$file,
'thumb_url' => $this->gallery_path_url.'thumbs/'.$file
);
}
return $images;
}
}
View:
<?php if ( is_array($images) && (count($images)>0) ):
foreach($images as $image): ?>
<div class="thumb">
<a href="<?php echo $image['url']; ?>">
<img src ="<?php echo $image['thumb_url']; ?>"/>
</a>
<br>
</div>
<?php endforeach; else: ?>
<div id = "blank_gallery">Please upload an Image</div>
<?php endif; ?>
Thanks again for all the help guys
Correct me if I'm wrong here but it seems you never assing $images to the view. You assign $image and $profileimages to index() but nay do I see $images.
You should Change your if in your view to
if(isset($images) && is_array($images))
that way if $images in undefined it will nto throw an error it will just skip that all together

Categories