how to upload image in codeigniter 3 - php

i have trouble with uploading an image using codeigniter. i am new in this and didin't have a clue in how to upload image using codeigniter. so i hope any of you guys can help me out
this is my form named form_add.php
<form method="POST" action="<?php echo base_url()."index.php/crud/insert"; ? >">
<table style="width:110%" class="table table-striped table table-bordered table table-hover">
<td>Nama</td>
<td><input type="text" name="nama_produk"/></td>
</tr>
<tr>
<td>Info</td>
<td><input type="text" name="info_produk"/></td>
</tr>
<tr>
<td>Harga</td>
<td><input type="text" name="harga_produk"/></td>
</tr>
<tr>
<td>Stock</td>
<td><input type="text" name="stock"/></td>
</tr>
<?php echo form_open_multipart('upload/do_upload');?>
<tr>
<td>Gambar</td>
<td><input type="file" name="gambar_produk"></td>
</tr>
<tr>
<td>Di Buat Oleh</td>
<td><input type="text" name="penulis_produk"/></td>
</tr>
<tr>
<td>Kategori</td>
<td><input type="text" name="kategori"/></td>
</tr>
<tr>
<td>Kode Kategori</td>
<td><input type="text" name="kode_kategori"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="btnsubmit" value="Simpan" /></td>
</tr>
</table>
</form>
and this is my controller named crud.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Crud extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index(){
$data = $this->mymodel->GetAll();
$this->load->view('view_all_produk',array('data' => $data));
}
public function add_data(){
$this->load->view('form_add');
}
public function insert(){
$nama_produk = $_POST['nama_produk'];
$info_produk = $_POST['info_produk'];
$harga_produk = $_POST['harga_produk'];
$stock = $_POST['stock'];
$penulis_produk = $_POST['penulis_produk'];
$gambar_produk = $_FILES['gambar_produk']['name'];
$gambar_tmp = $_FILES['gambar_produk']['tmp_name'];
$kategori = $_POST['kategori'];
$kode_kategori = $_POST['kode_kategori'];
$data_insert = array(
'nama_produk' => $nama_produk,
'info_produk' => $info_produk,
'harga_produk' => $harga_produk,
'stock' => $stock,
'penulis_produk' => $penulis_produk,
'gambar_produk' => $gambar_produk,
'kategori' => $kategori,
'kode_kategori' => $kode_kategori
);
$res = $this->mymodel->insertData('produk',$data_insert);
if($res >= 1){
$this->session->set_flashdata('pesan','Tambah Data Sukses');
redirect('crud/index');
}else{
echo "<h2>Insert Data Gagal!!!</h2>";
}
}
public function do_upload()
{
$config['upload_path'] = './assets/images';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 300;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('gambar_produk'))
{
$error = array('error' => $this->upload- >display_errors());
$this->load->view('form_add', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
}
}
and this is the model named mymodel.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mymodel extends CI_Model {
public function GetAll($where="") {
$data = $this->db->query('select * from produk '.$where);
return $data -> result_array();
}
public function insertData($tableName,$data){
$res = $this->db->insert($tableName,$data);
return $res;
}
public function updateData($tableName,$data,$where){
$res = $this->db->update($tableName,$data,$where);
return $res;
}
public function GetKategori($where=""){
$data = $this->db->query('select * from kategori '.$where);
return $data;
}
}
also this is what it shows after i run it
A PHP Error was encountered
Severity: Notice
Message: Undefined index: gambar_produk
Filename: controllers/crud.php
Line Number: 30
Backtrace:
File: C:\xampp\htdocs\genstore\admin\application\controllers\crud.php
Line: 30
Function: _error_handler
File: C:\xampp\htdocs\genstore\admin\index.php
Line: 315
Function: require_once
A PHP Error was encountered
Severity: Notice
Message: Undefined index: gambar_produk
Filename: controllers/crud.php
Line Number: 31
Backtrace:
File: C:\xampp\htdocs\genstore\admin\application\controllers\crud.php
Line: 31
Function: _error_handler
File: C:\xampp\htdocs\genstore\admin\index.php
Line: 315
Function: require_once
A Database Error Occurred
Error Number: 1048
Column 'gambar_produk' cannot be null
INSERT INTO produk (nama_produk, info_produk, harga_produk, stock, penulis_produk, gambar_produk, kategori, kode_kategori) VALUES ('sada', 'asdas', 'asdasd', 'sdasd', 'sdasd', NULL, 'sadasd', '14')
Filename: C:/xampp/htdocs/genstore/admin/system/database/DB_driver.php
Line Number: 691
so can anyone tell me what's my mistake? thanks

Are you using multipart on the form?
<?php echo form_open_multipart('upload/do_upload');?>
https://www.codeigniter.com/userguide3/libraries/file_uploading.html
Edit: i see you are, there's a form within a form in your code!!

try this ! Send form-data encoded as "multipart/form-data":
<form method="POST" action="<?php echo base_url()."index.php/crud/insert"; ?>" enctype="multipart/form-data">
<table style="width:110%" class="table table-striped table table-bordered table table-hover">

Related

Laravel 5.2 - Upload Files to Database

These are what I have :
Database table named lamanInformasi, which has these fields: id, judul, isi, created_at, updated_at.
This is what I want :
User can upload multiple document or image files, and the files will be stored to database. The file names will be saved to isi field, and the files itself will be saved to a folder named propic. User also can show all the data from database on the website.
These are my codes :
create.blade.php
<form action="lamanInformasiController#index" method="post" enctype="multipart/form-data">
<input type="file" name="image"><br />
<input type="submit" name="submit" value="Submit">
</form>
lamanInformasiController.php
public function index(Request $request)
{
$file = new file;
if (Input::hasFile('image'))
{
$destinationPath = public_path().'/propic/';
$name = Input::file('image')->getClientOriginalName();
$extension = Input::file('image')->getClientOriginalExtension();
$file = Input::file('image')->move($destinationPath, $name . "." . $extension);
}
$file -> isi = $request->get($file);
$file -> save();
$lamanInformasi = LamanInformasi::all();
return view('upload.index', compact('lamanInformasi'));
}
index.blade.php
<table class="table table-striped table-bordered" border= "1px solid black">
<thead>
<tr>
<td>ID</td>
<td>Judul</td>
<td>Isi</td>
<td>Created At</td>
<td>Updated At</td>
</tr>
</thead>
<tbody>
#foreach($$lamanInformasi as $key => $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->judul}}</td>
<td>{{$value->isi}}</td>
<td>{{$value->created_at}}</td>
<td>{{$value->updated_at}}</td>
</tr>
#endforeach
</tbody>
</table>
When I run it, I have this error :
ErrorException in ParameterBag.php line 90:
array_key_exists(): The first argument should be either a string or an integer
I have this in ParameterBag line 89-91
public function get($key, $default = null)
{
return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}
These are my questions :
How to fix that error? Did I make the code right to upload files? Because I have tried similar code, and it's not working. Thanks
There are a couple of things which you need to take care of. Try the code as below
LamanInformasiController.php - controller names are generally capitalized
class LamanInformasiController extends Controller
{
/**
* #var LamanInformasi - include the use statement above for the model.
*/
protected $model;
/**
* Inject (model)LamanInformasi while instantiating the controller.
* #param LamanInformasi $model
*/
public function __construct(LamanInformasi $model)
{
$this->model = $model;
}
public function index()
{
$lamanInformasi = $this->model->all();
return view('upload.index', compact('lamanInformasi'));
}
public function store(Request $request)
{
if (Input::hasFile('image'))
{
$destinationPath = public_path().'/propic/';
$name = Input::file('image')->getClientOriginalName();
$extension = Input::file('image')->getClientOriginalExtension();
$fileName = $name.'.'.$extension;
//store the file in the $destinationPath
$file = Input::file('image')->move($destinationPath, $fileName);
//save a corresponding record in the database
$this->model->create(['isi'=> $fileName]);
//return success message
}
//return failure message
}
} //don't forget to include the use statement for Input or write \Input
Then in your index.blade.php
<table class="table table-striped table-bordered" border= "1px solid black">
<thead>
<tr>
<td>ID</td>
<td>Judul</td>
<td>Isi</td>
<td>Created At</td>
<td>Updated At</td>
</tr>
</thead>
<tbody>
#foreach($lamanInformasi as $file)
<tr>
<td>{{$file->id}}</td>
<td>{{$file->judul}}</td>
<td>{{$file->isi}}</td>
<td>{{$file->created_at}}</td>
<td>{{$file->updated_at}}</td>
</tr>
#endforeach
</tbody>
And your form action should be accordingly
<form action="/upload8" method="post" enctype="multipart/form-data">
<input type="file" name="image"><br />
<input type="submit" name="submit" value="Submit">
This should work, haven't tested though. Let me know if otherwise.

edit form validation error

when i am performing validation on edit form it gives an error:
undefined variable score_id on line no-16, and then for all variable that is student_name, subject_name, marks.
my controller file.
public function edit($id)
{
$this->load->library('form_validation');
$score_id = $this->uri->segment('3');
$this->form_validation->set_rules('std_name','student_name','trim|required|alpha');
$this->form_validation->set_rules('txt_name','subject_name','trim|required|alpha');
$this->form_validation->set_rules('marks','marks','required|numeric');
if ($this->form_validation->run() == FALSE)
{
$score_id = $this->uri->segment('3');
$this->load->view('edit_score');
}
elseif($this->input->post('edit') && $this->input->post('edit_id')!='')
{
$score_id = $this->uri->segment('3');
$data = array(
'score_id' => $this->input->post('score_id'),
'student_name' => $this->input->post('std_name'),
'subject_name' => $this->input->post('txt_name'),
'marks' => $this->input->post('marks'),
);
$result = $this->score->update_record($id,$data);
header('location:'.base_url().'index.php/score_listing');
}
if($id)
{
echo "this is score_id".$id;
$result = $this->score->edit_score($id);
$data['action'] = 'edit';
$data['score_id'] = $result[0]->score_id;
$data['student_name'] = $result[0]->student_name;
$data['subject_name'] = $result[0]->subject_name;
$data['marks'] = $result[0]->marks;
}
echo "welome to edit page";
$this->load->view('edit_score',$data);
}
this is my edit file
<h1>Edit score</h1>
<?php $action = $score_id!='' ? 'edit/'.$score_id : 'add'; ?>
<form name="edit_score" method="post" action="<?php echo $action; ?>">
<input type="hidden" name="score_id" value="<?php echo $score_id;?>"/>
<?php echo form_hidden('admin_id',$this->load->session->userdata('admin_id')); ?>
<!--for above function use form helper in controller file -->
<table style="width:100%" border="0">
<tr>
<td>student Name:</td>
<td><input type="text" name="std_name" value="<?php echo $student_name; ?>"/></td>
<?php echo form_error("std_name"); ?>
</tr>
<tr>
<td>subject Name:</td>
<td><input type="text" name="txt_name" value="<?php echo $subject_name; ?>"/></td>
<?php echo form_error("txt_name"); ?>
</tr>
<tr>
<td>max marks:</td>
<td><input type="text" name="marks" value="<?php echo $marks; ?>" /></td>
<?php echo form_error("marks"); ?>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="edit" value="Submit"/></td>
</tr>
</table>
</form>
my uri is: http://localhost/ci/index.php/score_listing/edit/1
it gives following error:
Edit score
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: score_id
Filename: views/edit_score.php
Line Number: 16
Backtrace:
File: D:\xampp\htdocs\ci\application\views\edit_score.php
Line: 16
Function: _error_handler
File: D:\xampp\htdocs\ci\application\controllers\score_listing.php
Line: 64
Function: view
File: D:\xampp\htdocs\ci\index.php
Line: 292
Function: require_once
At first time load or when validation false it will run this code
if ($this->form_validation->run() == FALSE)
{
$score_id = $this->uri->segment('3');
$this->load->view('edit_score');
}
Here array argument not passed to view file like this $this->load->view('edit_score',$data);. So you have declare the null value or some other what you before the validation and should pass the array argument value
$data = array(
'score_id' => '',
'student_name' => '',
'subject_name' => '',
'marks' => '',
);
if ($this->form_validation->run() == FALSE)
{
$score_id = $this->uri->segment('3');
$this->load->view('edit_score',$data);// here is changes pass $data
}

Can not insert data in Mysql using codeigniter

I can not insert data into mysql because of database error 1048.I have been searching from almost 1 week, but i couldn't find any solution. please help me. Here is all the stuff...
controller users.php:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller
{
function __construct()
{
parent::__construct();
#$this->load->helper('url');
$this->load->model('users_model');
}
public function index()
{
$data['user_list'] = $this->users_model->get_all_users();
$this->load->view('show_users', $data);
}
public function add_form()
{
$this->load->view('insert');
}
public function insert_new_user()
{
$udata['Username'] = $this->input->post('name');
$udata['Email-Id'] = $this->input->post('email');
$udata['Address'] = $this->input->post('address');
$udata['Mobile'] = $this->input->post('mobile');
$res = $this->users_model->insert_users_to_db($udata);
if($res)
{
header("location: http://localhost/crudcode/index.php/users_model/insert_users_to_db");
}
else
{
echo "Hello";
}
}
}
Model users_model.php:
<?php
class Users_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_users()
{
$query = $this->db->get('users');
return $query->result();
}
public function insert_users_to_db($udata)
{
return $this->db->insert('users', $udata);
}
public function getById($id)
{
$query = $this->db->get_where('users',array('id'=>$id));
return $query->row_array();
}
}
?>
view insert.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CI Insert Form</title>
</head>
<body>
<form method="post" action="localhost/crudcode/index.php/users/insert_new_user">
<table width="400" border="0" cellpadding="5">
<tr>
<th width="213" align="right" scope="row">Enter your username</th>
<td width="161"><input type="text" name="name" size="20" /></td>
</tr>
<tr>
<th align="right" scope="row">Enter your email</th>
<td><input type="text" name="email" size="20" /></td>
</tr>
<tr>
<th align="right" scope="row">Enter your Mobile</th>
<td><input type="text" name="mobile" size="20" /></td>
</tr>
<tr>
<th align="right" scope="row">Enter Your Address</th>
<td><textarea name="address" rows="5" cols="20"></textarea></td>
</tr>
<tr>
<th align="right" scope="row"> </th>
<td><input type="submit" name="submit" value="Send" /></td>
</tr>
</table>
</form>
</body>
</html>
Here is the error
Have you check if the data from the form is submitted? like
public function insert_new_user()
{
print_r($this->input->post());
}
and check the array you've pass on the user model and the last query as well.
public function insert_users_to_db($udata)
{
$this->db->insert('users', $udata);
print_r($udata);
echo $this->db->last_query();
}
You Can try with changing the FORM action from
<form method="post" action="localhost/crudcode/index.php/users/insert_new_user">
TO
<form method="post" action="<?php echo base_url();?>index.php/users/insert_new_user" >
I am assuming you are not submitting an empty form.
The problem could be that there is a redirect happening which is not carrying your $POST data.
Have you tried using this as an action (with the right trailing /):
http://localhost/crudcode/index.php/users/insert_new_user/
You're calling the insert_user_to_db() twice.
First with:
$res = $this->users_model->insert_users_to_db($udata);
and in this call you're sending the values from the $udata array.
And then with:
if($res)
{
header("location: http://localhost/crudcode/index.php/users_model/insert_users_to_db");
}
and this call does not include any arguments so it's probably in this call it fails.
What happens if you exclude the second call and just to like this?
$res = $this->users_model->insert_users_to_db($udata);
echo print_r($res, true);
Genereally speaking you should not need/should not redirect to a model. Those kind of redirects should be handled by the controller(s).
1)Better to use form_open() and form_close().
2)Check Array which you are inserting.Columns names should match with the assoc array.
I believe Email-Id is an invalid field name. If you have named a field that way, you must escape it like:
`Email-Id`
or more accurately:
$udata['`Email-Id`'] = $this->input->post('email');
Though a much better solution is to rename the field, because that isn't even a naming convention. Either use only CamelCase or only underscore_names. A dash not a valid character for a field/variable name in any language I know of.

Uploading multiple images for single record in codeigniter

As questioned above I want to upload multiple images for single product into database table (table will contain only image paths).
My code is:
Controller - productController.php
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('productModel');
}
public function index()
{
$data['product_list'] = $this->productModel->get_all_products();
$this->load->view('productDisplay', $data);
}
public function add_form()
{
$this->load->view('insertProduct');
}
private function setup_upload_option()
{
$config = array();
$config['upload_path'] = './uploadProductImages/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['encrypt_type'] = true;
$config['overwrite'] = false;
return $config;
}
public function insert_new_product()
{
$this->load->library('upload');
$files = $_FILES;
$count = count($_FILES['images']['name']);
for($i=0;$i<$count;$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']['size'] = $files['images']['size'][$i];
$_FILES['images']['error'] = $files['images']['error'][$i];
$this->upload->initialize($this->setup_upload_option());
if($this->upload->do_upload() == false)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('insertProduct', $error);
}
else
{
$upload_data = $this->upload->data();
$udata['name'] = $this->input->post('name');
$udata['manufacturer'] = $this->input->post('manufacturer');
$udata['price'] = $this->input->post('price');
$udata['images'] = $upload_data['file_name'];
$res = $this->productModel->insert_products_to_db($udata);
if($res)
{
header('location:'.base_url()."index.php/productController/".$this->index());
}
}
}
Model - productModel.php
public function insert_products_to_db($data)
{
return $this->db->insert('product_info', $data);
}
View - insertProduct.php
<?php if(isset($error)){echo $error;}?>
<form method="post" action="<?php echo base_url();?>index.php/productController/insert_new_product" enctype="multipart/form-data">
<table >
<tr>
<th >Product Name</th>
<td ><input type="text" name="name" /></td>
</tr>
<tr>
<th >Manufacturer</th>
<td><input type="text" name="manufacturer" /></td>
</tr>
<tr>
<th >Price</th>
<td><input type="text" name="price"/></td>
</tr>
<tr>
<th >Images</th>
<td><input type="file" name="images[]" multiple=""/></td>
</tr>
<tr>
<th > </th>
<td><input type="submit" name="submit" value="Add" /></td>
</tr>
</table>
</form>
My database table contains 5 fields p_id, name, manufacturer,price and images. And after running this code, when I clicks on Add it do not show any error or do not redirect to controller but it stays on same page and no any image is present in uploadProductImages and also no new product will insert in database table.
Any help for this new learner will be appreciated.

Notice: Undefined index: in C:\wamp\www\somygms\a.php on line 142

I got an error whenever I run this php code on my local web server:
<?php
# require_once ('C:\wamp\www\Connections\koneksi.php');
session_start();
if (!isset($_SESSION['id']))
{
header("Location:index.php");
}
$sql = "SELECT * FROM pasien WHERE noreg = 1122312131";
$query = mysql_query($sql) or die(mysql_error());
$data2 = mysql_fetch_array($query);
?>
<form id="form1" name="form1" method="post" action="#">
<table width="804" border="0" id="inputdata" style="border-collapse:collapse">
<tr>
<th width="8" rowspan="3" bgcolor="#CCCCCC" scope="row"> </th>
<th width="104" height="50" bgcolor="#CCCCCC" scope="row"><div align="right">Kode Pasien</div></th>
<td width="250" bgcolor="#CCCCCC"><label for="nama"></label>
<label for="noreg"></label>
<div align="left">
<input name="noreg" type="text" id="noreg" size="15" maxlength="13">
<input type="submit" name="view" id="view" value="View"> <?php
# include_once ('database.php');
$view = $_POST['view'];
$noreg = $_POST['noreg'];
if($view){
$_POST[$noreg];
}
?>
This is the error:
( ! ) Notice: Undefined index: view in C:\wamp\www\somygms\a.php on line 139
and
( ! ) Notice: Undefined index: noreg in C:\wamp\www\somygms\a.php on line 140
Thanks for any help, will be appreciated.
-admin
You are initializing those two variables with the array item does not exists.
$view = $_POST['view'];
$noreg = $_POST['noreg'];
Clearly shows that the view and noreg are not coming from the POST method. You should check to confirm this. Use var_dump($_POST); to see the posted data.
When you are coding, you should make sure that the code you are writing will execute on all cases as much as possible. In your case, initialize the variables before or use isset to check and initialize again.
$view = isset($_POST['view']) ? $_POST['view'] : '';
$noreg = isset($_POST['noreg']) ? $_POST['noreg'] : '';
Now that it is being pointed out.... The page by default will have *no POST variables *, so you have filter such cases out
if(isset($_POST) && count($_POST)) {
# include_once ('database.php');
$view = $_POST['view'];
$noreg = $_POST['noreg'];
if($view){
$_POST[$noreg];
}
}
Its because of you accessing a key in $_POST that doesnt exist. Try the following:
$view = (isset($_POST['view']) ) ? $_POST['view'] : '';
$noreg = (isset($_POST['noreg']) ) ? $_POST['noreg'] : '';
Call to a member function fetch() on a non-object in C:\wamp\www\chat\chat_vue.php on line 3

Categories