can't upload image to database in codeigniter - php

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"

Related

While inserting multiple images to database more than one row are added in main table which is connected to images table

I'm trying to upload multiple image in codeigniter. For a particular product I want to add the uploaded images to another table calles"image".... while using "lastid" so that I get pid(product id from table product_multi) in images multiples rows are inserted in the product_multi table... the number rows is according to the number of images I upload. Someone help me to fix this.. If I'm not using lastid variable passing it works perfectly/... but I want pid in images tables :(
This is how im getting datable
This is my model
<?php
class ProductmModel extends CI_Model
{
var $PRODUCTNAME='';
var $DESCRIPTION='';
var $CATEGORY='';
var $SUBCAT='';
var $IMAGE='';
public function addproductm()
{
$this->load->database();
$data = array(
"p_name" => $this->PRODUCTNAME,
"p_des" => $this->DESCRIPTION,
"cat" => $this->CATEGORY,
"subcat" => $this->SUBCAT
);
$this->db->insert('product_multi', $data);
$lastid=$this->db->insert_id();
echo "$lastid";
return $lastid;
}
public function addimage()
{
$last=$this->addproductm();
$this->load->database();
$data = array(
"pid" =>$last,
"images" => $this->IMAGE
);
$this->db->insert('image', $data);
}
}
controller code::
public function upload()
{
//image upload
$config['upload_path'] = './images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload',$config);
$this->upload->initialize($config);
$fileInfos = array();
$errors = array();
//uploading
if (! empty($_FILES['images']['name']))
{
$photosCount = count($_FILES['images']['name']);
for ($i = 0; $i < $photosCount; $i ++)
{
$_FILES['image']['name'] = $_FILES['images']['name'][$i];
$_FILES['image']['type'] = $_FILES['images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['images']['error'][$i];
$_FILES['image']['size'] = $_FILES['images']['size'][$i];
if ($this->upload->do_upload('image'))
{
array_push($fileInfos, array(
'fileInfo' => $this->upload->data()
));
$filename =$_FILES['image']['name'] ;
//$filename =$_FILES["name"].$_FILES["type"];
// $data['fileInfos'] = $fileInfo;
$this->load->model("ProductmModel");
$this->ProductmModel->IMAGE = $filename;
}
else
{
array_push($errors, array(
'error' => $this->upload->display_errors()
));
}
}
}
$pname = $this->input->post("name");
$pdes = $this->input->post("pdes");
$caty = $this->input->post("category");
$subcat = $this->input->post("subcat");
$this->ProductmModel->PRODUCTNAME = $pname;
$this->ProductmModel->DESCRIPTION = $pdes;
$this->ProductmModel->CATEGORY = $caty;
$this->ProductmModel->SUBCAT = $subcat;
$this->ProductmModel->addproductm();
}
This is the code after editing as u said...making both insertion in single function
exampleee:
public function upload(){
//image upload
$config['upload_path'] = './images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload',$config);
$this->upload->initialize($config);
$fileInfos = array();
$errors = array();
//uploading
if (! empty($_FILES['images']['name']))
{
$photosCount = count($_FILES['images']['name']);
for ($i = 0; $i < $photosCount; $i ++)
{
$_FILES['images']['name'] = $_FILES['images']['name'][$i];
$_FILES['images']['type'] = $_FILES['images']['type'][$i];
$_FILES['images']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
$_FILES['images']['error'] = $_FILES['images']['error'][$i];
$_FILES['images']['size'] = $_FILES['images']['size'][$i];
if ($this->upload->do_upload('images'))
{
$data = $this->upload->data();
array_push($fileInfos, $data['file_name']);
}
else{
array_push($errors, array(
'error' => $this->upload->display_errors()
));
}
}
}
$product_array = array(
"p_name" => $this->input->post("name"),
"p_des" => $this->input->post("pdes"),
"cat" => $this->input->post("category"),
"subcat" => $this->input->post("subcat")
);
$this->ProductmModel->addproductm($product_array, $fileInfos);
}
Model
public function addproductm($product_array, $fileInfos){
$this->load->database();
$this->db->insert('product_multi', $product_array);
$lastid = $this->db->insert_id();
foreach($fileInfos as $file){
$image_data = array(
"pid" => $lastid,
"images" => $file
);
$this->db->insert('image', $image_data);
}
}

How to upload my file and photo and add to databases

I want to upload a picture.
I wrote a codes for this ... but this photo is not added to the database at all. And Just, "else" is executed.
public function store(Request $request){
//Get Request Input
$name = $request ->input('name');
$description = $request ->input('description');
$cover_image = $request ->file('cover_image');
$owner_id = 1;
//Check Image Upload
if($cover_image)
{
$cover_image_filename = $cover_image -> getClientOriginalName();
$cover_image -> move(public_path('images'), $cover_image_filename);
}
else{
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')-> insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id
]
);
//Redirect
return \Redirect::route('gallery.index') -> with('message', 'Gallery Created');
}`
what's the wrong?
1) Make sure you have added enctype="multipart/form-data" in your form and a <input type="file"> with field name="cover_image"
2) Create a new folder named images in your laravel public folder.
3) In your controller
public function store(Request $request){
//Get Request Input
$name = $request ->input('name');
$description = $request ->input('description');
$owner_id = 1;
//Check Image Upload
if( $request->hasFile('cover_image')) {
$cover_image = $request->file('cover_image');
$path = public_path(). '/images/';
$cover_image_filename = $cover_image->getClientOriginalName();
$cover_image->move($path, $cover_image_filename);
}
else{
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')-> insert([
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id
]);
//Redirect
return \Redirect::route('gallery.index') -> with('message', 'Gallery Created');
}
Hope it's helpful.

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

Codeigniter: How to upload files path to database?

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();
}

Categories