Updating image in database using file upload - php

I am trying to update my database through a form which includes updating the stored image in the database but it doesnt work nothing happens if i click the upload button it just redirects me
my view :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Test</title>
</head>
<body>
<div class="container">
<div class="row" >
<?php echo form_open_multipart('edit_news/update_news'); ?>
<div class="col-md-10">
<br>
<div class="panel panel-default">
<div class="panel-body">
<?php if (validation_errors()): ?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<?php echo validation_errors(); ?>
</div>
<?php endif ?>
<?php foreach ($news as $n): ?>
<form action="<?php echo base_url() . "edit_news/update_news/". $n->news_id; ?>" method="post" class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-2 control-label" style=" color: white"></label>
<label class="col-sm-2 control-label">Product Image</label>
<div class="col-sm-5">
<input type="file" class="form-control" placeholder="" name="userfile">
</div>
</div>
<br>
<br> <br>
<div class="form-group"> <label class="col-sm-2 control-label" ></label>
<label class="col-sm-2 control-label" >Product ID:</label>
<div class="input-group dis" style="width: 320px;">
<input value="<?php echo $n->news_id; ?>" disabled="" type="text" class="form-control " aria-describedby="sizing-addon2" id="id" name="id">
</div>
</div>
<div class="form-group"> <label class="col-sm-2 control-label" ></label>
<label class="col-sm-2 control-label" >Product Title:</label>
<div class="input-group dis" style="width: 320px;">
<input value="<?php echo $n->title; ?>" type="text" class="form-control " aria-describedby="sizing-addon2" id="name" name="title">
</div>
</div>
<div class="form-group"> <label class="col-sm-2 control-label" ></label>
<label class="col-sm-2 control-label" >Product Description:</label>
<div class="input-group dis" style="width: 320px;">
<input value="<?php echo $n->news_description; ?>" type="text" class="form-control " aria-describedby="sizing-addon2" id="price" name="description">
</div>
</div>
<?php echo form_error('serial'); ?>
<div class="col-sm-offset-0 col-sm-12"><label class="col-sm-4 control-label" ></label>
<button type="button, submit" class="btn btn-primary " style="border-radius: 0;">
Upload
</button>
</div>
<?php endforeach; ?>
<?php echo form_close() ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="<?= base_url(); ?>js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#myTable').dataTable();
});
</script>
</body>
</html>
controller:
public function update_news(){
$config['upload_path'] = './assets/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200000';
$config['max_width'] = '200000';
$config['max_height'] = '200000';
$config['new_image'] = './assets/';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->form_validation->set_rules('title', 'News Title', 'required|xss_clean');
$this->form_validation->set_rules('description', 'News Description', 'required|xss_clean');
if (!$this->upload->do_upload() || !$this->form_validation->run()) {
$error = array('error' => $this->upload->display_errors());
redirect('admin_news_adds');
} else {
$data = $this->upload->data();
$this->thumb($data);
$id = $this->uri->segment(3);
$file = array(
'img_name' => $data['raw_name'],
'thumb_name' => $data['raw_name'] . '_thumb',
'ext' => $data['file_ext'],
'news_date' => date("l , F j, Y "),
'title' => $this->input->post('title'),
'status' => 1,
'news_description' => $this->input->post('description'),
);
$this->User->update_news($file,$id);
$data = array('upload_data' => $this->upload->data());
redirect('admin_news_add');
}
}
model:
public function update_news($file,$id) {
$this->db->where('news_id',$id);
$this->db->update('news_table', $file);
}

Maybe any error when you upload the image, you can debug your php source why error happened, like adding var_dump($error) in 1st condition (if (!$this->upload->do_upload() || !$this->form_validation->run()) ) and comment "redirect('admin_news_adds');" just for debugging condition.
public function update_news(){
$config['upload_path'] = './assets/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200000';
$config['max_width'] = '200000';
$config['max_height'] = '200000';
$config['new_image'] = './assets/';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->form_validation->set_rules('title', 'News Title', 'required|xss_clean');
$this->form_validation->set_rules('description', 'News Description', 'required|xss_clean');
if (!$this->upload->do_upload() || !$this->form_validation->run()) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
//redirect('admin_news_adds');
} else {
$data = $this->upload->data();
$this->thumb($data);
$id = $this->uri->segment(3);
$file = array(
'img_name' => $data['raw_name'],
'thumb_name' => $data['raw_name'] . '_thumb',
'ext' => $data['file_ext'],
'news_date' => date("l , F j, Y "),
'title' => $this->input->post('title'),
'status' => 1,
'news_description' => $this->input->post('description'),
);
$this->User->update_news($file,$id);
$data = array('upload_data' => $this->upload->data());
redirect('admin_news_add');
}
}

You have two forms. First when you call form
<?php echo form_open_multipart('edit_news/update_news'); ?>
And inside foreach block
<form action="<?php echo base_url() . "edit_news/update_news/". $n->news_id; ?>"
method="post" class="form-horizontal" role="form">
which contain Button element. Because uploading need form attribute enctype set to multipart/form-data, your inner form does not have this so no file upload took place.

Try this
public function update_news()
{
$this->load->library('upload');
$config['upload_path'] = getcwd().'/assets/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200000';
$config['max_width'] = '200000';
$config['max_height'] = '200000';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
$this->form_validation->set_rules('title', 'News Title', 'required|xss_clean');
$this->form_validation->set_rules('description', 'News Description', 'required|xss_clean');
if (!$this->upload->do_upload() || !$this->form_validation->run()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('your view name', $error);
} else {
$data = $this->upload->data();
$this->thumb($data);
$id = $this->uri->segment(3);
$file = array(
'img_name' => $data['raw_name'],
'thumb_name' => $data['raw_name'] . '_thumb',
'ext' => $data['file_ext'],
'news_date' => date("l , F j, Y "),
'title' => $this->input->post('title'),
'status' => 1,
'news_description' => $this->input->post('description'),
);
$this->User->update_news($file,$id);
$data = array('upload_data' => $this->upload->data());
redirect('admin_news_add');
}
}

Related

My Input File Think the Input Is Still Empty Even Though I Have chosen A File

I'm currently working with upload system with Codeigniter 4 and Bootstrap 4.6x. Everything works fine except this one. So my idea was the user needs to upload a screenshot for my leaderboard web app. But the problem was, when I tested it for upload image (it should be an image), every time I chose the file, the input did not work, or the input did not receive a file I chose, to be precise.
Here is my form :
<div class="row">
<div class="col-8">
<h1 class="my-3">Upload Highscore Anda!</h1>
<form action="/highscore/upload_post" method="POST" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="form-group row">
<label for="score" class="col-sm-2 col-form-label">Score</label>
<div class="col-sm-10">
<input type="text" class="form-control <?= ($validation->hasError('score') ? 'is-invalid' : '' ); ?>" id="score" name="score" autofocus>
<div class="invalid-feedback">
<?= $validation->getError('score'); ?>
</div>
</div>
</div>
<p>THE PROBLEM BELONGS HERE (i think)</p>
<div class="form-group row">
<label for="image" class="col-sm-2 col-form-label">Screenshot</label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" class="custom-file-input <?= ($validation->hasError('image') ? 'is-invalid' : '' ); ?>" name="image" id="image" multiple="multiple">
<div class="invalid-feedback">
<?= $validation->getError('image'); ?>
</div>
<label class="custom-file-label" for="image">Choose file</label>
</div>
</div>
</div>
<p>END OF PROBLEM</p>
<div class="form-group row-4">
<select name="game" class="custom-select mr-sm-2 <?= ($validation->hasError('game') ? 'is-invalid' : '' ); ?>" id="game">
<!-- yang diambil nanti valuenya. misal milih one, nanti kalo $game = $this->req->getVar('game'); hasilnya 1 -->
<option selected disabled>Pilih Game...</option>
<?php foreach($games as $g) : ?>
<option value="<?= $g['id']; ?>"><?= $g['name']; ?></option>
<?php endforeach; ?>
</select>
<div class="invalid-feedback">
<?= $validation->getError('game'); ?>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Post</button>
</div>
</div>
</form>
</div>
</div>
My controller for uploading :
I've changed the request with req in $this->req->getVar because of some error
public function upload() {
$games = $this->games_model->findAll();
if ($this->session->get('logged_in') == true && $this->session->get('level') == 'user') {
$data = [
'title' => 'Upload',
'session_data' => $this->session->get(),
'games' => $this->games,
'games' => $games,
'validation' => $this->validation
];
return view('upload', $data);
}
return redirect()->to('/login');
}
public function upload_post() {
$score = $this->req->getVar('score');
$image = $this->req->getFiles();
$game = $this->req->getVar('game');
if(!$this->validate([
'score' => [
'rules' => 'required',
'errors' => [
'required' => 'Score tidak boleh kosong'
]
],
'image' => [
'rules' => 'required|uploaded[image]|max_size[image,5120]|is_image[image]|mime_in[image,image/jpg,image/jpeg,image/png]',
'errors' => [
'required' => 'Screenshot tidak boleh kosong',
'uploaded' => 'Pilih gambar sampul terlebih dahulu',
'max_size' => 'Maksimal ukuran gambar adalah 5MB',
'is_image' => 'Yang Anda pilih bukan gambar',
'mime_in' => 'Yang Anda pilih bukan gambar'
]
],
'game' => [
'rules' => 'required',
'errors' => [
'required' => 'Game tidak boleh kosong'
]
]
])) {
return redirect()->to('/upload')->withInput();
}
// $this->post_model->save([
// 'image' => $image,
// 'score' => $score,
// 'user_email' => $this->session->get('email'),
// 'game_id' => $game
// ]);
}
Thank you in advance
Here is an example of a working file upload.
<form class="form-horizontal" action="/" method="post" enctype="multipart/form-data">
<input type="file" class="form-control" name="myFile" id="myFile" size="20">
<button type="submit">
Save
</button>
</form>
Php code
<?php
$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'] . "/your_path";
$config['max_size'] = 0;
$config['allowed_types'] = '*';
// if you want to set custom file name
$new_name = time() . $_FILES["medicalFile"]['name'];
$config['file_name'] = $new_name;
// end file name set
$this->load->library('upload', $config);
$this->upload->do_upload('myFile');
Change this $image = $this->req->getFiles();
To
$image = $this->req->getFiles('image');

Codeigniter File Upload and save path to database with other form contents

This is my controller file that receives input from view file. post data will be submited to Add function and the function manipulates do upload function which recieves configuration parameters from set_configuration_function.
public function __construct()
{
parent::__construct();
$this->load->model('App/AppModel');//load app model
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
}
public function index()
{
$this->data['blogs'] = $this->AppModel->get_all(BLOGS_TABLE);
parent::LOADER('App/Blog/All');
}
public function Add()
{
if ($_POST && empty($_FILES['blog_file']['name'])) {
$new_blog = $_POST;
$this->AppModel->insert(BLOGS_TABLE, $new_blog);
$this->session->set_flashdata('flashSuccess', 'Blog Created Successfully.');
$this->index();
}
if ($_POST && !empty($_FILES['blog_file']['name'])) {
$file_name =$this->do_upload();
$file_name = array($file_name);
$blog = $_POST;
$new_blog = array_merge($blog, $file_name);
$this->AppModel->insert(BLOGS_TABLE, $new_blog);
$this->session->set_flashdata('flashSuccess', 'Blog Created Successfully.');
$this->index();
}
parent::LOADER('App/Blog/New');
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
public function set_upload_options (){
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '10000000000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
return $config;
}
This is my View File
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header col-md-offset-1">
<h1>
<?php echo BLOG_HEADING; ?>
<small><?php echo ADD; ?></small>
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<!-- right column -->
<div class="col-md-8 col-md-offset-1">
<!-- general form elements disabled -->
<div class="box box-warning">
<div class="box-header with-border">
<h3 class="box-title"><?php echo ADD; ?> Blog</h3>
</div>
<!-- /.box-header -->
<?php echo form_open_multipart('App/Blog/Add');?>
<div class="box-body">
<!-- text input -->
<!-- input states -->
<div class="form-group has-success">
<label class="control-label" for="inputSuccess"> <?php echo BLOG_TITLE; ?> *</label>
<input type="text" name="blog_title" class="form-control" id="inputSuccess" placeholder="Enter Title" required>
</div>
<div class="form-group has-success">
<label class="control-label" for="inputSuccess"> <?php echo BLOG_AUTHOR; ?> *</label>
<input type="text" name="blog_author" class="form-control" id="inputSuccess" placeholder="Enter Author" required>
</div>
<div class="form-group has-success">
<label class="control-label" for="inputSuccess"> <?php echo BLOG_URL; ?></label>
<input type="text" name="blog_url" class="form-control" id="inputSuccess" placeholder="Add Link" required>
</div>
<!-- textarea -->
<div class="form-group has-success">
<label class="control-label" for="inputSuccess"><?php echo BLOG_CONTENT; ?> *</label>
<textarea name="blog_content" class="form-control" rows="3" placeholder="Enter Content" required></textarea>
</div>
<div class="form-group has-success">
<label for="exampleInputFile">Blog Image</label>
<input type="file" name="blog_file" id="exampleInputFile">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary"><?php echo SAVE; ?></button>
</div>
</form>
</div>
</div>
</section>
</div>
Problem is I get error that says "you did not select a file to upload."
you are not using set_upload_options() method.
you are missing input name blog_file in your controller.
$this->upload->do_upload('blog_file');

How to upload picture using codeigniter?

I can manage to insert data into the tblaccount. But the problem is the picture can't be uploaded. The tblaccount contains the right data of firstname, lastname, email, department, username, and password, but the picture remains blank even I've uploaded some images.
UPDATE: The picture can now be uploaded in the folder, but no luck in tblaccount. It only show blank data.
signup.php controller:
public function index()
{
// set form validation rules
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|alpha|min_length[3]|max_length[30]');
$this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email|is_unique[tblaccount.Email]');
$this->form_validation->set_rules('department', 'Department', 'trim|required|alpha|min_length[3]|max_length[30]');
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha|min_length[3]|max_length[30]|is_unique[tblaccount.Username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('picture', 'Image', 'trim|required');
// submit
if ($this->form_validation->run() == FALSE)
{
// fails
$this->load->view('signup_view');
}
else
{
if(!empty($_FILES['picture']['name']))
{
$config['upload_path'] = './uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 10000000;
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture'))
{
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}
else
{
$picture = '';
$error = array('error' => $this->upload->display_errors());
echo "<script>alert('JPG, JPEG, PNG and GIF type of file only is allowed and atleast 10MB of size');window.location = '".base_url("index.php/signup")."';</script>";
}
}
else
{
$picture = '';
}
$data = array(
'First_Name' => $this->input->post('firstname'),
'Last_Name' => $this->input->post('lastname'),
'Email' => $this->input->post('email'),
'Department' => $this->input->post('department'),
'Username' => $this->input->post('username'),
'Password' => $this->input->post('password'),
'Picture' => $picture
);
if ($this->account_model->insert($data))
{
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are successfully registered! Please login to access your profile!</div>');
redirect('login');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('signup');
}
}
}
signup.php view:
<div class="row">
<div class="col-md-4 col-md-offset-4 well">
<?php echo form_open_multipart('signup');?>
<legend>Signup</legend>
<div class="form-group">
<label for="name">First Name</label>
<input class="form-control" name="firstname" placeholder="First Name" type="text" value="<?php echo set_value('First_Name');?>"/>
<span class="text-danger"><?php echo form_error('firstname'); ?></span>
</div>
<div class="form-group">
<label for="name">Last Name</label>
<input class="form-control" name="lastname" placeholder="Last Name" type="text" value="<?php echo set_value('Last_Name');?>"/>
<span class="text-danger"><?php echo form_error('lastname'); ?></span>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input class="form-control" name="email" placeholder="Email Address" type="text" value="<?php echo set_value('Email');?>"/>
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<label for="email">Department</label>
<input class="form-control" name="department" placeholder="Department" type="text" value="<?php echo set_value('Department');?>"/>
<span class="text-danger"><?php echo form_error('department'); ?></span>
</div>
<div class="form-group">
<label for="email">Username</label>
<input class="form-control" name="username" placeholder="Username" type="text" value="<?php echo set_value('Username');?>"/>
<span class="text-danger"><?php echo form_error('username'); ?></span>
</div>
<div class="form-group">
<label for="subject">Password</label>
<input class="form-control" name="password" placeholder="Password" type="password"/>
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="form-group">
<label for="subject">Confirm Password</label>
<input class="form-control" name="cpassword" placeholder="Confirm Password" type="password"/>
<span class="text-danger"><?php echo form_error('cpassword'); ?></span>
</div>
<div class="form-group">
<label for="subject">Profile Picture:</label>
<input class="form-control" name="picture" accept="image/*" type="file"/>
<span class="text-danger"><?php echo form_error('picture'); ?></span>
</div>
<div class="form-group">
<button name="submit" type="submit" class="btn btn-info">Signup</button>
<button name="cancel" type="reset" class="btn btn-info">Cancel</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
Remove required from validation check as it is not allowed to pass in image field ,when you check empty file field (!empty($_FILES['picture']['name']) then required validation already checked inside it , Secondly you have to check whether the directory is created or not and provide 777 permission to it . I have tested code by adding only these two check. Hope it help
$this->form_validation->set_rules('picture', 'Image', 'trim'); /*Change in this line -- remove required*/
if ($this->form_validation->run()) {
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/images/';
/*add 777 permission to directory*/
if (!is_dir($config['upload_path'])) {
mkdir($config['upload_path'], 0777, TRUE);
}
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 10000000;
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
$error = array('error' => $this->upload->display_errors());
echo "<script>alert('JPG, JPEG, PNG and GIF type of file only is allowed and atleast 10MB of size');window.location = '" . base_url("index.php/signup") . "';</script>";
}
} else {
$picture = '';
}
$data = array(
'image' => $picture
);
$this->write_conn->db->insert('test', $data);
if ($this->write_conn->db->insert('test', $data)) {
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">You are successfully registered! Please login to access your profile!</div>');
} else {
// error
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
}
}
On your upload path
$config['upload_path'] = 'uploads/images/';
Try
$config['upload_path'] = './uploads/images/';
$config['upload_path'] = FCPATH . '/uploads/images/';
And I use form_open_multipart() form helper make sure your folder correct permissions
On another note make sure you have named your file and class name correct where signup.php would be Signup.php Only the first letter should be uppercase on class and filename explained here https://www.codeigniter.com/user_guide/general/styleguide.html#file-naming
<?php
class Signup extends CI_Controller {
}

Uploading in codeigniter doesn't work. what can be the reason?

This is the controller, and i have no errors
public function admin_page(){
if($this->input->post('add_product')){
if(empty($_FILES['userfile']['name'])){
$data = array(
'category' => $this->input->post('category') ,
'product_name' => $this->input->post('name') ,
'description' => $this->input->post('description'),
'image' => 'no_image.jpg'
);
} else{
$config['upload_path'] = './public/images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|JPG';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
echo 'uploaded :)';
$data = array(
'category' => $this->input->post('category') ,
'product_name' => $this->input->post('name') ,
'description' => $this->input->post('description'),
'image' => $_FILES['userfile']['name']
);
}
$this->load->model('products');
$this->products->add_product($data);
}
$this->load->view('admin_page');
}
View
<form action="<?php echo base_url();?>admin/admin_page" method="post" enctype="multipart/form-data">
<div class="col-xs-3">
<div class="form-group">
<label for="exampleInputEmail1"> Product name </label>
<input type="text" name="name" class="form-control" >
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Category </label>
<input type="text" name="category" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Description </label>
<textarea class="form-control" name="description" rows="3"></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Image </label>
<input type="file" name="userfile" class="form-control">
</div>
<input type="submit" name="add_product" class="btn btn-default" value="OK" />
</div>
</form>
</div>
Note: Things to check on codeigniter 3.
Make sure the controller and model name has first letter upper case
Admin.php and class Admin extends CI_Controller {
And model Products.php and class Products extends CI_Model {
CI2 Upload http://www.codeigniter.com/userguide2/libraries/form_validation.html
CI3 Upload http://www.codeigniter.com/user_guide/libraries/file_uploading.html
Controller
<?php
class Admin extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('upload');
//$this->load->model('products');
}
public function index() {
}
public function admin_page() {
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if ($this->form_validation->run() == FALSE) {
$data['upload_errors'] = $this->upload->display_errors();
$this->load->view('admin_page', $data);
} else {
/*
* If userfile checks if.
*
*/
if (!empty($_FILES['userfile']['name'])) {
/*
*
* Make sure your images upload path is on the main directory
*
* application
* public
* public > images
* system
* .htaccess
* index.php
*
*/
$config['upload_path'] = './public/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '3000';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->upload->initialize($config);
$field_name = 'userfile';
if ( ! $this->upload->do_upload($field_name)) {
$data['upload_errors'] = $this->upload->display_errors();
$this->load->view('admin_page', $data);
} else {
/*
* Using the variable below you are able to get codeigniter file upload info.
* Note: Codeigniter upload only made for one file
* $upload_data = $this->upload->data();
*
*/
$upload_data = $this->upload->data();
$data = array(
'category' => $this->input->post('category') ,
'product_name' => $this->input->post('name') ,
'description' => $this->input->post('description'),
'image' => $upload_data['file_name']
);
$this->products->add_product($data);
$data['upload_errors'] = '';
$this->load->view('admin_page', $data);
}
/*
If no image isset
*/
} else {
echo "No File Isset";
$data = array(
'category' => $this->input->post('category') ,
'product_name' => $this->input->post('name') ,
'description' => $this->input->post('description'),
'image' => 'no_image.jpg'
);
$this->products->add_product($data);
$data['upload_errors'] = '';
$this->load->view('admin_page', $data);
}
}
}
}
View
Changed input submit to button submit.
<div class="container">
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php if ($upload_errors) {?>
<div class="alert alert-info"><?php echo $upload_errors;?></div>
<?php }?>
<?php echo form_open_multipart('admin/admin_page');?>
<div class="form-group">
<label>Product name</label>
<input type="text" name="name" class="form-control" value="<?php echo set_value('name');?>" size="50">
</div>
<div class="form-group">
<label>Category</label>
<input type="text" name="category" value="<?php echo set_value('category');?>" class="form-control" size="50">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" name="description" rows="3"></textarea>
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="userfile" size="20">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Save</button>
</div>
<?php echo form_close();?>
</div>
I would use codeigniter's form_open_multipart() http://www.codeigniter.com/user_guide/helpers/form_helper.html
All working my end.

It is possible in codeigniter to have more than 1 input/browse file for different image upload in a single form to save all in 1 table in a db?

I am an newbie here and i need help so badly with my research project. I have no clue about uploading multiple image to different field in database using codeigniter. I have tried so many way past a few days but still failed..
My question is, it is possible in codeigniter to have more than one input/browse file for image button in a single form to save all in one table in a database. I have two text fields and I want different images for each one. I want to save one or more than one images with 1st text box and one or more than one images with the second text box in single form.
My current error is only 1 image success uploaded to field and another field is null.
My Controller:
public function create(){
//form validation sebelum mengeksekusi QUERY INSERT
$this->form_validation->set_rules('nama', 'Nama Property', 'required');
$this->form_validation->set_rules('deskripsi_singkat', 'Deskripsi Singkat', 'required');
$this->form_validation->set_rules('deskripsi_lengkap', 'Deskripsi Lengkap', 'required');
$this->form_validation->set_rules('harga_range', 'Price Range', 'required|integer');
$this->form_validation->set_rules('unit', 'Total Unit', 'required|integer');
//$this->form_validation->set_rules('userfile', 'Product Image', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('backend/form_tambah_product');
} else {
//load uploading file library
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '300'; //MB
$config['max_width'] = '2000'; //pixels
$config['max_height'] = '2000'; //pixels
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('gambar'))
{
//file gagal diupload -> kembali ke form tambah
$this->load->view('backend/form_tambah_product');
} else {
$upload_data = $this->upload->data();
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '300'; //MB
$config['max_width'] = '2000'; //pixels
$config['max_height'] = '2000'; //pixels
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('gambar1'))
{
//file gagal diupload -> kembali ke form tambah
$this->load->view('backend/form_tambah_product');
} else {
$upload_data2 = $this->upload->data();
}
//file berhasil diupload -> lanjutkan ke query INSERT
// eksekusi query INSERT
$data_product = array(
'nama' => set_value('nama'),
'deskripsi_singkat' => set_value('deskripsi_singkat'),
'deskripsi_lengkap' => set_value('deskripsi_lengkap'),
'harga_range' => set_value('harga_range'),
'unit' => set_value('unit'),
'image'=>$upload_data['file_name'],
'blok_plan'=>$upload_data2['file_name']
);
$this->model_products->create($data_product);
}
}
View:
<div><?= validation_errors() ?></div>
<?= form_open_multipart('products/create', ['class'=>'form-horizontal']) ?>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Nama Property</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="nama" placeholder="" value="<?= set_value('nama') ?>">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Deskripsi Singkat</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="deskripsi_singkat" placeholder="" value="<?= set_value('deskripsi_singkat') ?>">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Deskripsi Lengkap</label>
<div class="col-sm-10">
<textarea class="form-control" name="deskripsi_lengkap"><?= set_value('deskripsi_lengkap') ?></textarea>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Price Range</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="harga_range" placeholder="" value="<?= set_value('harga_range') ?>">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Total Unit</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="unit" placeholder="" value="<?= set_value('unit') ?>">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Property Image</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="gambar" >
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Blok Plan</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="gambar1" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Save</button>
</div>
</div>
<?= form_close() ?>
</div>
<div class="col-md-1"></div>
</div>
<script>
$(document).ready(function(){
$('#myTable').DataTable();
});
</script>
Model:
public function create($data_products){
//Query INSERT INTO
$this->db->insert('list_properti',$data_products);
}
Use jquery for this or you can use select2 or chosen library. See how to use select2 for Multiple input:
https://select2.github.io/examples.html.
If you know the way how to use jquery and basic php, you will do this.
Finally, thanks guys for the reference.
public function create(){
//form validation sebelum mengeksekusi QUERY INSERT
$this->form_validation->set_rules('nama', 'Nama Property', 'required');
$this->form_validation->set_rules('deskripsi_singkat', 'Deskripsi Singkat', 'required');
$this->form_validation->set_rules('deskripsi_lengkap', 'Deskripsi Lengkap', 'required');
$this->form_validation->set_rules('harga_range', 'Price Range', 'required|integer');
$this->form_validation->set_rules('unit', 'Total Unit', 'required|integer');
//$this->form_validation->set_rules('userfile', 'Product Image', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('backend/form_tambah_product');
} else {
//load uploading file library
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '300'; //MB
$config['max_width'] = '2000'; //pixels
$config['max_height'] = '2000'; //pixels
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('gambar'))
{
//file gagal diupload -> kembali ke form tambah
$this->load->view('backend/form_tambah_product');
} else {
$upload_data = $this->upload->data();
$config2['upload_path'] = './uploads/';
$config2['allowed_types'] = 'jpg|png';
$config2['max_size'] = '300'; //MB
$config2['max_width'] = '2000'; //pixels
$config2['max_height'] = '2000'; //pixels
$this->load->library('upload', $config2);
$this->upload->initialize($config2);
if ( ! $this->upload->do_upload('gambar1'))
{
//file gagal diupload -> kembali ke form tambah
$this->load->view('backend/form_tambah_product');
} else {
$upload_data2 = $this->upload->data();
//file berhasil diupload -> lanjutkan ke query INSERT
// eksekusi query INSERT
$data_product = array(
'nama' => set_value('nama'),
'deskripsi_singkat' => set_value('deskripsi_singkat'),
'deskripsi_lengkap' => set_value('deskripsi_lengkap'),
'harga_range' => set_value('harga_range'),
'unit' => set_value('unit'),
'image'=>$upload_data['file_name'],
'blok_plan'=>$upload_data2['file_name']
);
$this->model_products->create($data_product);
}
redirect('products');
}
}
}

Categories