uploading image and data in mysql table in codeigniter - php

I'm trying to upload an image with a car make, year, lease and payment data
along with the image upload. My image path is also inserted to the DB but i still cant figure how to combine both.
Im getting an error Array to string conversion and its not inputting my data and image upload.
cars table:
car_make | car_model | car_year | car_lease | car_payment | imgpath
acura | G37 Sedan | 2009 | 48 | 350 | assets/images/acura_1.jpg
controller:
public function car_validation_do_upload() {
$this->load->library('form_validation');
$this->form_validation->set_rules('car_make', 'Car Make', 'required');
$this->form_validation->set_rules('car_model', 'Car Model', 'required');
$this->form_validation->set_rules('car_year', 'Car Year', 'required');
$this->form_validation->set_rules('car_lease', 'Car Lease', 'required');
$this->form_validation->set_rules('car_payment', 'Car Payment', 'required');
if($this->form_validation->run() == TRUE) {
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpeg|jpg|png';
$this->load->library('upload', $config);
$newRow = array("car_make" => $this->input->post('car_make'),
"car_model" => $this->input->post('car_model'),
"car_year" => $this->input->post('car_year'),
"car_lease" => $this->input->post('car_lease'),
"car_payment" => $this->input->post('car_payment'));
$data = array('upload' => $this->upload->data());
$result = array_merge($newRow, $data);
$this->load->model("model_users");
$this->model_users->insert1($result);
$this->session->set_flashdata('message', 'car inserted into database!');
redirect('main/insertCar');
}
else {
$this->load->view('insert_car');
}
}
Model:
public function insert1($data) {
$this->db->insert("cars", $data);
}
View
<?php
//echo form_open('main/car_validation_insert');
echo form_open_multipart('main/car_validation_do_upload');
echo validation_errors();
if($this->session->flashdata('message')){
echo $this->session->flashdata('message');
}
?>
<table width="504" style="margin-left:15px;">
<tr>
<td colspan="2"><p class="table-title">Insert Car</p></td>
<td></td>
</tr>
<tr>
<td>Car Make: </td>
<td><input type="text" name="car_make" class="textbox" tabindex="1"/></td>
<td> </td>
</tr>
<tr>
<td>Car Model:</td>
<td><input type="text" name="car_model" class="textbox" tabindex="2"/></td>
<td> </td>
</tr>
<tr>
<td>Car Year:</td>
<td><input type="text" name="car_year" class="textbox" tabindex="3"/></td>
<td> </td>
</tr>
<tr>
<td>Car Lease:</td>
<td><input type="text" name="car_lease" class="textbox" tabindex="4"/></td>
<td> </td>
</tr>
<tr>
<td>Car Payment:</td>
<td><input type="text" name="car_payment" class="textbox" tabindex="5"/></td>
<td> </td>
</tr>
<tr>
<td>Car Image:</td>
<td><input type="file" name="userfile" size="20" /></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<input type="submit" name="submit" value="submit" id="button" class="button" style="margin-left:140px;" />
<?php
echo form_close();
?>

Change this:
$data = array('upload' => $this->upload->data());
$result = array_merge($newRow, $data);
To this:
if ($this->upload->do_upload()){
$image_data = $this->upload->data();
//this will create a new key with the name upload in your newRow
//so theres no need to use the function array_merge
$newRow['imgpath'] ='assets/images/'.$image_data['file_name'];
}
else{
//do something here
echo 'error uploading image'
}
The $image_data variable will have this information about your uploaded image
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[client_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
You can find all the information about the file upload class on the user guide of codeingiter:
http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

Related

Codeigniter - can’t upload image through input type file

I am creating recipe book in PHP Codeigniter. I have a problem with uploading image to resource folder and save image path to dtb. All the data successfully save to database except file (image).
View.
<?php echo form_open_multipart('Recipes/add'); ?>
<table style="padding: 15px;">
<tr>
<td><label for="title">Title:</label></td>
<td><input type="text" name="title" id="title" name="title" required/></td>
</tr>
<tr>
<td><label for="category">Category:</label></td>
<td>
<select id="category" name="category">
<?php
foreach($categories as $row1){
print "<option value=" . $row1->id . ">";
print $row1->title;
print "</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td><label for="ingredients">Ingredients:</label></td>
<td><textarea name="ingredients" id="ingredients" required></textarea></td>
</tr>
<tr>
<td> <label for="production_method">Production method:</label></td>
<td><textarea name="production_method" id="production_method" required></textarea></td>
</tr>
<tr>
<td> <label for="production_time">Production time:</label></td>
<td><input type="production_time" name="production_time" id="production_time" required/> minutes</td>
</tr>
<tr>
<td> <label for="image_path">Upload an image:</label></td>
<td><input type="file"name="image_path"></td>
</tr>
<tr>
<td> <input type="submit" value="Save recipe" id="submit" name="submit"/></td>
<td> <input type="reset" value="Reset" id="reset" /></td>
</tr>
</table>
<?php echo form_close(); ?>
Controller
class Recipes extends CI_Controller{
public function __construct(){
//call CodeIgniter's default Constructor
parent::__construct();
//load database libray manually
$this->load->database();
//load Model
$this->load->model('Recipe_model');
$this->load->helper(array('form', 'url'));
//load registration view form
$this->load->model("Category_model");
}
public function add(){
$data['categories']= $this->Category_model->get_categories();
//call a function of the loaded view
$this->load->view("templates/header");
//we load a view to display the results
$this->load->view("new_insert",$data);
$this->load->view("templates/footer");
$config['upload_path'] = "/CI/assets/imgs/";
$config['allowed_types'] = "gif|jpg|png|jpeg";
$this->load->library('upload', $config);
//Check submit button
if($this->input->post('submit')){
// if ($this->upload->do_upload('image_path')){
//get form's data and store in local varable
$title=$this->input->post('title');
$category=$this->input->post('category');
$ingredients=$this->input->post('ingredients');
//$image_path=$this->input->post('image_path');
$this->upload->do_upload('image_path');
$image_path= $this->upload->data();
$production_method=$this->input->post('production_method');
$production_time=$this->input->post('production_time');
$this->Recipe_model->form_insert([
'title' => $title,
'category_id' => $category,
'ingredients' => $ingredients,
'production_method' => $production_method,
'production_time' => $production_time,
'image_path' => $image_path['image_path']
]);
redirect("Recipes/dispdata");
}
}
I tried to use Codeigniter documentation, but couldn’t work. I will be very greatful for every response, I am new in MVC. Thank you.

How to update image with form hidden?

Hi all I am a new codeigniter .I have create code update image with form hidden but I have problam the from hidden not passing value to form image userfile :( Iam very need help now ?or could anyone give the source code about update image in to database on codigniter.
<form action="<?php echo base_url()."./site_admin/update_menu/".$this->uri->segment(3); ?>" method="post" enctype="multipart/form-data">
<?php
$id = $this->uri->segment(3);
$sql = $this->db->get_where('menu',array('id_menu' => $id));
$row = $sql->row(); ?>
<?php $idcat = $row->cate_id ?>
<table class="tab" style="width:100%">
<tr>
<td>Categories Name:</td>
<td>
<select style="padding:6px;background:#C2C2C2;font-weight: bold;" name="cate">
<?php
$query = $this->db->get('categories_menu');
foreach($query->result() as $lazy){
$select = "";
if($lazy->id == $idcat){
$select = "selected";
}
echo "<option $select value='".$lazy->id."'>".$lazy->cate_name_menu."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Upload image:</td>
<td><input type="file" name="userfile" style="width:190px;height:35px;font-weight: bold;background:#C2C2C2;" ></td>
<td><input type="hidden" name="mono" value="<?php echo $row->image; ?>"></td>
</td>
</tr>
<tr>
<td>Title:</td>
<td><textarea class="title" name="title" cols="100" rows="4"><?php echo $row->title; ?></textarea></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="15" name="description" class="dess" ><?php echo $row->description; ?></textarea><td>
</tr>
<tr>
<td>Prices</td>
<td><textarea class="price" name="price" cols="40" rows="4"><?php echo $row->prices; ?></textarea></td>
</tr>
<tr>
<td></td>
<td>
<input style="width:100px; padding:10px;font-weight: bold;background:#1F1F1F;color:white;" type="submit" value="Submit" name="submit">
</td>
</tr>
</table>
</form>
Controller:
function update_menu(){
$id = $this->uri->segment(3);
$img1 = $this->input->post('userfile');
$img2 = $this->input->post('mono');
if($img1 == ""){
$img1 = $img2;
$datas = array(
'cate_id' => $this->input->post('cate'),
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
'prices' => $this->input->post('price'),
'image' => $img1
);
$this->db->where('id_menu', $id);
$this->db->update('menu',$datas);
redirect('./site_admin/edit_menu/'.$id);
}else{
$id = $this->uri->segment(3);
$updata = array(
'upload_path' => './images/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '5000',
'max_width' => '4000',
'max_height' => '2800'
);
$this->load->library('upload',$updata);
$this->upload->do_upload('userfile');
$nampic = $this->upload->data();
$data = array(
'cate_id' => $this->input->post('cate'),
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
'prices' => $this->input->post('price'),
'image' => $nampic['file_name']
);
$this->db->where('id_menu', $id);
$this->db->update('menu',$data);
redirect('./site_admin/edit_menu/'.$id);
}
}

How change html View of ZF1 captcha

i am not using captcha in zend form i am directly writting zend captch code on controller. My code is:
IndexController.php
public function loginAction(){
$this->view->assign('action',"/sabkuch/index/auth");
$this->view->assign('user','username');
$this->view->assign('passwd','Password');
//$a=$this->_helper->Comman->textEmail("hi........","htm body.......","pkr","from#gm.com","xyz","xyz#gm.com");
//echo $a; die;
// Our form object...
// And here's our captcha object...
$captcha = new Zend_Form_Element_Captcha('captcha',
array('label' => 'Write the chars to the field',
'captcha' => array( // Here comes the magic...
// First the type...
'captcha' => 'Image',
'useNumbers' => true,
'fontSize' => '22',
'wordLen' => '4',
'height' => '57',
'width' => '235',
// Captcha timeout, 5 mins
'timeout' => 300,
// What font to use...
'font' => APPLICATION_PATH . '/../public/font/6.ttf',
// Where to put the image
'imgDir' => APPLICATION_PATH . '/../public/captcha/',
// URL to the images
// This was bogus, here's how it should be... Sorry again :S
'imgUrl' => 'http://localhost/sabkuch/public/captcha/',
)));
$this->view->captcha = $captcha;
}
Login.phml
<table width="100%" border="0" cellspacing="0" cellpadding="1">
<form class="form_align" name="login" method="post" action="<?php echo $this->escape($this->action);?>">
<tbody>
<tr>
<td align="left"><strong><?php echo $this->escape($this->user);?></strong></td>
</tr>
<tr>
<td align="left"><?php echo $this->formText('username', '', array(
'class' => 'textfield',
'alt' => 'NOBLANK~loginEmail~DM~',
'size' => '30',
)
); ?>
</td>
</tr>
<tr>
<td align="left"><strong><?php echo $this->escape($this->passwd);?></strong></td>
</tr>
<tr>
<td align="left"><?php echo $this->formPassword('passwd', '', array(
'class' => 'textfield',
'alt' => 'NOBLANK~loginEmail~DM~',
'size' => '30',
)
); ?>
</td>
</tr>
<tr>
<td align="left"><strong>Set Captcha</strong></td>
</tr>
<tr>
<td align="left"><?php
echo $this->captcha->render($this, null) ;
?>
</td></tr>
<tr>
<td align="left" style="padding-top:5px">
<?php echo $this->formHidden('id', 'login'); ?>
<input type="submit" name="submit" value="Submit"> </td>
</tr>
</tbody>
</form>
</table>
captch code output is
<dd id="captcha-element">
<img width="235" height="57" alt="" src="http://localhost/sabkuch/public/captcha/770eec95f4b247754b4b6c30cd74a4a4.png" />
<input type="hidden" name="captcha[id]" value="770eec95f4b247754b4b6c30cd74a4a4" id="captcha-id" />
<input type="text" name="captcha[input]" id="captcha-input" value="" /></dd>
i need captcha html output as per my requirement like
<tr><td> <dd id="captcha-element">
<img width="235" height="57" alt="" src="http://localhost/sabkuch/public/captcha/770eec95f4b247754b4b6c30cd74a4a4.png" />
<input type="hidden" name="captcha[id]" value="770eec95f4b247754b4b6c30cd74a4a4" id="captcha-id" />
</tr></td>
<tr><td>
<input type="text" name="captcha[input]" id="captcha-input" value="" /></dd>
</tr></td>
in zend form we cn add decoratro but i am directly using this captcha on controller How i change this ouput of html

Undefined Index: file_upload [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
Below is my Code:
<?php
require_once("includes/initialize.php");
if (!$session->is_logged_in()) { redirect_to("../index.php"); }
include_template("admin_header.php");
$product = new Products;
?>
<?php
$upload_errors = array(
// http://www.php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
if(isset($_POST['submit'])) {
if($_POST['productname'] == "" || $_POST['price'] == "" || $_POST['origin'] == "" || $_POST['description'] == "") {
$message = "All fields are compulsary";
} else {
$errors = array();
$now = time();
$product->product_name = $_POST['productname'];
$product->price = $_POST['price'];
$product->origin = $_POST['origin'];
$product->description = $_POST['description'];
$product->img1 = $now."_".basename($_FILES['img1']['name']);
$product->img2 = ($now+1)."_".basename($_FILES['img2']['name']);
$product->visibility = $_POST['visibility'];
// process the form data
$tmp_file = $_FILES['img1']['tmp_name'];
$target_file = $product->img1;
$tmp_file1 = $_FILES['img2']['tmp_name'];
$target_file1 = $product->img2;
$upload_dir = "images";
// move_uploaded_file will return false if $tmp_file is not a valid upload file
// or if it cannot be moved for any other reason
if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file) && move_uploaded_file($tmp_file1, $upload_dir."/".$target_file1)) {
$product->create();
$message = "Product uploaded successfully. <br />";
} else {
echo "<pre>".print_r($_FILES,true)."</pre>";
$error = $_FILES['file_upload']['error'];
$message = $upload_errors[$error];
}
}
}
?>
<tr>
<td bgcolor="989797"><table width="1000" border="0">
<tr bgcolor="#999999">
<th width="750" valign="top" bgcolor="#999999" scope="col"><table width="100%" cellspacing="0" id="bodytable">
<tr>
<td></td>
</tr>
<tr class="bodytitle">
<td colspan="2" valign="top"><strong>Add Product!!</strong></td>
</tr>
<tr>
<td width="100%" valign="top"><div id="text2">
<div>
<table width="100%" cellspacing="0">
<tr>
<td colspan='2'>
<?php
if(isset($message)) {
echo "<font size='2'>".$message."</font>";
}
?>
</td>
</tr>
<tr>
<td align='left' colspan='2'><font size='2'>File Size must be less than 1mb</font></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<form name="form1" enctype="multipart/form-data" action="addproduct.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
<td align='left'><font size='2'>Product Name:</font></td>
<td align='left'><input name='productname' type='text' /></td>
</tr>
<tr>
<td align='left'><font size='2'>Price:</font></td>
<td align='left'><input name='price' type='text' /></td>
</tr>
<tr>
<td align='left'><font size='2'>Origin:</font></td>
<td align='left'><input name='origin' type='text' /></td>
</tr>
<tr>
<td align='left'><font size='2'>Description:</font></td>
<td align='left'><textarea name='description' rows='5' cols='35' /></textarea></td>
</tr>
<tr>
<td align='left'><font size='2'>Visibility</font></td><td align='left'>
<select name='visibility' rows='50' />
<option value='1'>Visible</option>
<option value='0'>Invisible</option>
</select>
</td>
</tr>
<tr>
<td align='left'><font size='2'>Image 1:</font></td>
<td align='left'><input name='img1' type='file' /></td>
</tr>
<tr>
<td align='left'><font size='2'>Image 2:</font></td>
<td align='left'><input name='img2' type='file' /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td align='left'><input name='submit' type='submit' value='Add!!' /></td>
</tr>
</form>
</table>
</div>
</div></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table></th>
<?php
include_template("admin_footer.php");
?>
I am getting error:
Notice: Undefined index: file_upload in ..\admin\addproduct.php on line 48
Notice: Undefined index: in ..\admin\addproduct.php on line 49
Which is:
if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file) && move_uploaded_file($tmp_file1, $upload_dir."/".$target_file1)) {
$product->create();
$message = "Product uploaded successfully. <br />";
} else {
echo "<pre>".print_r($_FILES,true)."</pre>";
$error = $_FILES['file_upload']['error'];
$message = $upload_errors[$error];
}
When I use echo "".print_r($_FILES,true)."";
I get:
Array
(
[img1] => Array
(
[name] => IMG_6527.JPG
[type] =>
[tmp_name] =>
[error] => 2
[size] => 0
)
[img2] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
Please help me out..
Thank you..
Your file is stored under img2 in the $_FILES array and not under file_upload.
So your line has to be
$error = $_FILES['img2']['error'];
That's because you give the index name for the $_FILES array here with the attribute name
<td align='left'><input name='img2' type='file' /></td>
You have to check if a file is uploaded as moeed-farooqui mentioned in his answer.
If it's optional
if(isset($_FILES['img2'])){
// only do something if a file is uploaded
}
Or if it's required
if(isset($_FILES['img2'])){
// handle the uploaded file
} else {
// genereate an error message cause no file was uploaded
}
use isset to chech either the value is set or not
if(isset($_FILES['xyz'])){
// your code here
}
In addition to this, I cant find any field having name file_upload.
It should be:
$error = $_FILES['img2']['error'];

input multiple value to one row in codeigniter

I have 3 pieces of the column, which I will inserting in one table in my database. The name of each form like this:
<h3><?= $title; ?></h3><?php echo form_open("admin/artikel/buat/");?>
<table width="95%">
<tr>
<td><b>Pilih Referensi Jurnal</b></td>
<td>
<input type="hidden" name="IDJurnal" id="IDJurnal" value="<?php echo $IDJurnal; ?>" />
<input type="text" name="volume" id="volume" value="<?php echo $volume; ?>" readonly="readonly" class="sedang" />
<?php echo anchor_popup('admin/artikel/popup', 'Referensi Jurnal', array('class' => 'button')); ?>
</td>
</tr>
<tr>
<td><b>Kategori</b></td>
<td>
<?php
echo form_dropdown('IDKategori', $kategori) . "";
?>
</td>
</tr>
<tr>
<td width="125"><strong>Judul</strong></td>
<td><input type="text" name="judul" class="panjang"></td>
</tr>
<tr>
<td width="125"><strong>Pengarang</strong></td>
<td>
<input type="text" name="pengarang" class="panjang">
<input type="text" name="pengarang" class="panjang">
<input type="text" name="pengarang" class="panjang">
</td>
</tr>
<tr>
<td><b>Abstract</b></td>
<td>
<?php
$data = array('name' => 'abstract');
echo $this->ckeditor->editor($data['name']);
?>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" class="button" value="Simpan">
<input type="button" class="button" value="Batal" onClick="javascript: history.go(-1)" />
</td>
</tr>
<?php
echo form_close();
?>
i want inserting the value from each form name to my sql table, like this:
CREATE TABLE `pengarang`(
`IDPengarang` INT(11)NOT NULL AUTO_INCREMENT,
`IDArtikel` INT(11)NOT NULL,
`nama_pengarang` VARCHAR(255)NOT NULL,
PRIMARY KEY(`IDPengarang`))ENGINE = INNODB DEFAULT CHARSET = utf8;
in my model like this:
function addArtikel() {
$now = date("Y-m-d H:i:s");
$data = array(
'IDJurnal' => $this->input->post('IDJurnal'),
'IDKategori' => $this->input->post('IDKategori'),
'judul' => $this->input->post('judul'),
'abstract' => $this->input->post('abstract'),
'created_time' => $now,
'created_by' => $_SESSION['username']
);
// $data1 = array(
// 'IDJurnal' => $this->input->post('IDJurnal'),
// 'IDKategori' => $this->input->post('IDKategori'),
// 'judul' => $this->input->post('judul'),
// 'abstract' => $this->input->post('abstract'),
// 'created_time' => $now,
// 'created_by' => $_SESSION['username']
// );
// $data2 = array(
// 'IDArtikel' => $this->input->post('IDArtikel'),
// 'nama_pengarang' => $this->input->post('pengarang')
// );
$this->db->insert('artikel', $data);
// $this->db->insert_batch('artikel', $data1);
// $this->db->insert_batch('pengarang', $data1);
}
in my controller
function buat() {
if ($this->input->post('judul')) {
$this->MArtikel->addArtikel();
$this->session->set_flashdata('message', 'Artikel telah di buat !');
redirect('admin/artikel/index', 'refresh');
} else {
// konfigurasi ckfinder dengan ckeditor
$this->load->library('ckeditor');
$this->load->library('ckfinder');
$this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
$this->ckeditor->config['toolbar'] = 'Full';
$this->ckeditor->config['language'] = 'en';
$this->ckfinder->SetupCKEditor($this->ckeditor, '../../../asset/ckfinder/');
$data['title'] = "Tambah Artikel";
$data['main'] = 'admin/artikel/artikel_buat';
$data['jurnal'] = $this->MJurnal->getJurnalDropDown();
$data['kategori'] = $this->MKategori->getKategoriDropDown();
$this->load->vars($data);
$this->load->view('dashboard/template');
}
}
What should I add to my controller and my model, that would make the results in my table looks like this
IDPengarang IDArtikel nama_pengarang
1 1 testing 1
2 1 testing 2
3 1 testing 3
thank's before

Categories