can anyone help me?
when im trying to upload image using codeigniter file uploading class just like in
http://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload
but i always encounter this error
localhost http 500 error
please anyone help me.
this is my controller
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_view', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}}
And this is my view upload_view.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<input type="submit" value="upload" />
<?php form_close(); ?>
</body>
</html>
and upload_success.php
<html>
<head>
<title> Image Upload </title>
</head>
<body>
<div id="container">
<dl>
<dt>
File Name:
</dt>
<dd>
<?php echo $uploadInfo['file_name'];?>
</dd>
<dt>
File Size:
</dt>
<dd>
<?php echo $uploadInfo['file_size'];?>
</dd>
<dt>
File Extension:
</dt>
<dd>
<?php echo $uploadInfo['file_ext'];?>
</dd>
<br />
<p>The Image:</p>
<img alt="uploaded image" src="<?=base_url(). 'uploads/' . $uploadInfo['file_name'];?>">
</dl>
</div>
</body>
</html>
Change your folder file permission to chmod -R 777 foldername
Related
This is my controller with index function and index2 function to upload two images
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Upload_Files extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('file');
}
function index(){
$data = array();
if($this->input->post('fileSubmit') && !empty($_FILES['userFiles']['name'])){
$filesCount = count($_FILES['userFiles']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->file->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
}
//Get files data from database
$data['files'] = $this->file->getRows();
//Pass the files data to view
$this->load->view('upload_files', $data);
}
function index2(){
$data = array();
if($this->input->post('fileSubmit2') && !empty($_FILES['userFiles']['name'])){
$filesCount = count($_FILES['userFiles']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];
$uploadPath = 'uploads/index2/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
$uploadData[$i]['divid'] =2;
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->file->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
}
//Get files data from database
$data['files'] = $this->file->getRows2();
//Pass the files data to view
$this->load->view('upload_files', $data);
}
}
This is my model to retrieve images from databases
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Model{
public function getRows($id = ''){
$this->db->select('id,file_name,created');
$this->db->from('files');
if($id){
$this->db->where('divid',1);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('created','desc');
$query = $this->db->get();
$result = $query->result_array();
}
return !empty($result)?$result:false;
}
public function insert($data = array()){
$insert = $this->db->insert_batch('files',$data);
return $insert?true:false;
}
public function getRows2($id = ''){
$this->db->select('id,file_name,created');
$this->db->from('files');
if($id){
$this->db->where('divid',2);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('created','desc');
$query = $this->db->get();
$result = $query->result_array();
}
return !empty($result)?$result:false;
}
public function insert2($data = array()){
$insert = $this->db->insert_batch('files',$data);
return $insert?true:false;
}
}
This is my view to upload 2 images and view those 2 images
<div class="container">
<div class="row">
<p><?php echo $this->session->flashdata('statusMsg'); ?></p>
<form enctype="multipart/form-data" action="<?php echo site_url('Upload_Files/index'); ?>" method="post">
<div class="form-group">
<label>Choose Files1</label>
<input type="file" class="form-control" name="userFiles[]" multiple/>
</div>
<div class="form-group">
<input class="form-control" type="submit" name="fileSubmit" value="UPLOAD"/>
</div>
</form>
</div>
<div class="row">
<ul class="gallery">
<?php if(!empty($files)): foreach($files as $file): ?>
<li class="item">
<img src="<?php echo base_url('uploads/files/'.$file['file_name']); ?>" alt="" >
<p>Uploaded On <?php echo date("j M Y",strtotime($file['created'])); ?></p>
</li>
<?php endforeach; else: ?>
<p>Image(s) not found.....</p>
<?php endif; ?>
</ul>
</div>
</div>
<div class="container">
<div class="row">
<p><?php echo $this->session->flashdata('statusMsg'); ?></p>
<form enctype="multipart/form-data" action="<?php echo site_url('Upload_Files/index2'); ?>" method="post">
<div class="form-group">
<label>Choose Files1</label>
<input type="file" class="form-control" name="userFiles[]" multiple/>
</div>
<div class="form-group">
<input class="form-control" type="submit" name="fileSubmit2" value="UPLOAD"/>
</div>
</form>
</div>
<div class="row">
<ul class="gallery">
<?php if(!empty($files)): foreach($files as $file): ?>
<li class="item">
<img src="<?php echo base_url('uploads/index2/'.$file['file_name']); ?>" alt="" >
<p>Uploaded On <?php echo date("j M Y",strtotime($file['created'])); ?></p>
</li>
<?php endforeach; else: ?>
<p>Image(s) not found.....</p>
<?php endif; ?>
</ul>
</div>
</div>
My problem is when I upload one image it appears in the other image view also. I tried so hard and put this question 2 times in stackoverflow. If someone helps me It will be a great thing
I am trying to make an insert function in codeigniter using php and bootstrap. But when i press add button, nothing happens, my new data are not added in my db table. Please Help me.
My code:
department.php
<?php
/*
* File Name: employee.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the employee model
$this->load->model('department_model');
}
//index function
function index()
{
//fetch data from department and designation tables
// $data['department'] = $this->department_model->get_department();
//set validation rules
$this->form_validation->set_rules('id', 'Employee ID', 'trim|required|numeric');
$this->form_validation->set_rules('department_emer', 'Department Name', 'trim|required|callback_alpha_only_space');
$this->form_validation->set_rules('pershkrimi', 'Description', 'trim|required');
//$this->form_validation->set_rules('id_departament', 'Department', 'callback_combo_check');
if ($this->form_validation->run() == FALSE)
{
//fail validation
$this->load->view('department_view');
}
else
{
//pass validation
$data = array(
//'id' => $this->input->post('id'),
'department_emer' => $this->input->post('department_emer'),
'pershkrimi' => $this->input->post('pershkrimi'),
);
//insert the form data into database
$this->db->insert('department', $data);
//display success message
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Department details added to Database!!!</div>');
redirect('department/index');
}
}
//custom validation function to accept only alpha and space input
function alpha_only_space($str)
{
if (!preg_match("/^([-a-z ])+$/i", $str))
{
$this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
department_model.php
<?php
/*
* File Name: employee_model.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get department table to populate the department name dropdown
}
?>
department_view.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter | Insert Employee Details into MySQL Database</title>
<!--link the bootstrap css file-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- link jquery ui css-->
<link href="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
<!--include jquery library-->
<script src="<?php echo base_url('assets/js/jquery-1.10.2.js'); ?>"></script>
<!--load jquery ui js file-->
<script src="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.js'); ?>"></script>
<style type="text/css">
.colbox {
margin-left: 0px;
margin-right: 0px;
}
</style>
<script type="text/javascript">
//load datepicker control onfocus
$(function() {
$("#hireddate").datepicker();
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-offset-3 col-lg-6 col-sm-6 well">
<legend>Add Department Details</legend>
<?php
$attributes = array("class" => "form-horizontal", "id" => "departmentform", "name" => "departmentform");
echo form_open("department/index", $attributes);?>
<fieldset>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="department_emer" class="control-label">Name</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="department_emer" name="department_emer" placeholder="department_emer" type="text" class="form-control" value="<?php echo set_value('department_emer'); ?>" />
<span class="text-danger"><?php echo form_error('department_emer'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="mbiemer" class="control-label">Description</label>
</div>
<div class="col-lg-8 col-sm-8">
<textarea class="form-control" rows="5" id="pershkrimi" name="pershkrimi" placeholder="pershkrimi" value="<?php echo set_value('pershkrimi'); ?>" ></textarea>
<span class="text-danger"><?php echo form_error('pershkrimi'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-md-8 text-left">
<input id="btn_update" name="btn_update" type="submit" class="btn btn-primary" value="Add" />
<input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
</body>
</html>
In department.php replace
$this->db->insert('department', $data);
with
$this->load->model('department_model.php');
$this->department_model.php->insert($data);
And in department_model.php create a function insert
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success message or anything which you want
}
}
This will solve your problem.
Let me know if you require any further help!!!
Please load the CI database library before inserting the data, or you can load it in your constructor method.
$this->load->library('database');
Hopefully it can help you.
Hi I am new with ajax and having problem. I am trying to make a shopping cart using ajax.I don't know what is wrong with my code please help me out.
When I click the add button an alert comes 'No success' and nothing happen , I am not able add items to cart.
Thanks for helping me.
This is my view
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $(this).serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping2/add",
dataType: 'json',
//type: "POST",
data: insert_data,
success:function(response) {
//if (response){
//var res = JSON.parse(response);
var res = response;
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping2";
}else{
alert(res.msg);
}
//}
//else{
// alert('sorry');
//}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<div id="addcart">
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping2/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well" id="addcart">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping2/remove'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr></div>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
</html>
This is my controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping2 extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_view2', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
//$success = $this->cart->insert($insert_data);
$cart_check = $this->cart->contents();
if(!empty($cart_check)){
//$this->cart->contents(insert_data);
$res = array('status' => 200, 'msg' => 'success');
}else{
$res = array('status' => 500, 'msg' => 'No success');
}
echo json_encode($res);
//echo $data[0]['value'];
//redirect('shopping2');
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
$this->cart->destroy();
}else{
$data = array(
'rowid' => $rowid,
'qty' => 0
);
$this->cart->update($data);
}
redirect('shopping2');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping2');
}
}
Please help me how to add items in the cart using ajax.
Since u managed to get a response, the problem should lie in your Model or data insertion.
Few suggestions:
It's also recommended that you use $.post() instead of $.ajax().
"<?php echo base_url(); ?>" + "index.php/shopping2/add" can be changed to "<?php echo site_url('shopping2/add"'); ?>"
Use the built in Codeignter output class to output your JSON. See here: https://www.codeigniter.com/userguide3/libraries/output.html
Hi i have called the database value in codeigniter controller and computed the values of database and stored in one new variable. So how can i get both the database values and the new variable that I have created in the controller as I want to display all database value and the new computed value in view. Please suggest me.
My controller: welcome
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public $total;
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->load->model('product_database');
}
public function index() {
$data['show_table'] = $this->view_table();
$this->load->view('welcome_message', $data);
}
public function view_table(){
$result = $this->product_database->show_all_data();
if ($result != false) {
return $result;
} else {
return 'Database is empty !';
}
}
public function AddtoCart(){
$id = $this->input->post('product_id');
$qty = $this->input->post('qty');
$this->db->where('id', $id); // Select where id matches the posted id
$query = $this->db->get('productlist', 1); // Select the products where a match is found and limit the query by 1
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => $row->name
);
$total=$qty*$row->price;
echo $total;
}
}
}
?>
my view: welcome_message
<!DOCTYPE HTML>
<html>
<head>
<title>Product list</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(event) {
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/Welcome/AddtoCart",
dataType: 'json',
data: {name: },
success: function(res) {
if (res)
{ alert();
// Show Entered Value
jQuery("#total").html(res.total);
}
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="message">
<?php
if (isset($read_set_value)) {
echo $read_set_value;
}
if (isset($message_display)) {
echo $message_display;
}
?>
</div>
<div> <?php
if (isset($show_table)) {
echo "<div class='productlist'>";
if ($show_table == 'Database is empty !') {
echo $show_table;
} else {
echo '<h2>Product List</h2><br/><br/>';
?>
<div class="row">
<div class="col-sm-8">
<div class="well">
<div class="table-responsive">
<?php
echo "<table width='98%', >";
echo '<tr><th class="e_id">Id</th><th>ProductName</th> <th>Price</th> <tr/>';
$i=1;
foreach ($show_table as $value) {
?>
<tr class="well" >
<?php
echo "<td width='30%' height='27px'>" . $value->id . "</td>" . "<td width='70%' height='27px'>" . $value->name . "</td>" . "<td height='27px'>" . $value->price . "</td>";
?>
<?php echo form_open('/Welcome/AddtoCart'); ?>
<td><input type="number" name="qty" value="1" style="width:40px;" min="1" max="99"></td>
<input type="hidden" name="product_id" value="<?php echo $value->id ?>" />
<td><input type="submit" value="Add" id="add" width="100%"></td>
<td><input type="submit" value="Rmv" id="rmv" width="100%"></td></br>
<?php echo form_close(); ?>
</tr>
<?php
$i=$i+1;}
echo '</table>';
?>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="well">
<h4>Cart</h4>
Total Rs:<input type="text" value="" id="total"></br><br>
<input type="submit" value="Checkout" id="chk_out">
</div>
</div>
</div>
<?php
}
echo "</div>";
}
?>
</div>
</div>
</body>
</html>
And my model
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Product_database extends CI_Model {
public function show_all_data() {
$this->db->select('*');
$this->db->from('productlist');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
}
?>
In place of echo $total you can put this code :
$total= array('total'=> $total);
$youarray=array_merge($data, $total);
echo json_econde($youarray,true);
I have the following form and controller where it has a image upload, but everything goes smooth except the file not being uploaded to the particular folder.
View
<?php
$this->load->helper('url');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>diluks eCommerce cms - home page</title>
<link href="<?php
echo base_url();
?>Public/scripts/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="<?php echo base_url();?>index.php/addproduct_controller" method="post">
<?php
include 'header-adminpanel.php';
?>
<div class="container">
<div class="body-content">
<div class="side-left"><?php
include 'adminproduct_sidebar.php';
?></div>
<div class="side-right">
<br />
<table>
<tr>
<td class="captions">Product Code</td>
<td><input name="txt_pcode" type="text"/></td>
</tr>
<tr>
<td class="captions">Product Name</td>
<td><input name="txt_pname" type="text" size="40" /></td>
</tr>
<tr>
<td class="captions">Product Price</td>
<td><input name="txt_pprice" type="text" /></td>
</tr>
<tr>
<td class="captions">Product Description</td>
<td><textarea name="txt_pdesc" style="width:300px;height:100px;"></textarea></td>
</tr>
<tr>
<td class="captions">Product Image</td>
<td><input type="file" name="userfile" size="20" /></td>
</tr>
<tr>
<td class="captions">Product Options</td>
<td><input name="txt_poptions" size="40" type="text" /><a class="hint"> (Separate by a "," comma)</a></td>
</tr>
<tr><td><input name="btn_add" class="button" type="submit" value="Add" /></td></tr>
</table>
<br />
</div>
</div>
</div>
<div style="clear:both"></div>
<?php
include 'footer.php';
?>
</form>
</body>
</html>
Controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Addproduct_controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
if (isset($_POST["btn_logout"])) {
$this->session->sess_destroy();
$this->load->view('welcome_view');
} else if (isset($_POST["btn_home"])) {
$this->load->view('welcome_view');
} else if (isset($_POST["btn_account"])) {
} else if (isset($_POST["btn_add"])) {
$prod_img = 'no image';
$config['upload_path'] = 'Public/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
// $error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
//return 'error';
} else {
global $prod_img;
$data = array(
'upload_data' => $this->upload->data()
);
$prod_img = $data->file_name;
// $this->load->view('upload_success', $data);
}
$prod_name = $_POST["txt_pname"];
$prod_code = $_POST["txt_pcode"];
$prod_price = $_POST["txt_pprice"];
$prod_desc = $_POST["txt_pdesc"];
$prod_options = $_POST["txt_poptions"];
$this->load->model('product_model');
$addproduct_result = $this->product_model->addProduct($prod_code, $prod_name, $prod_price, $prod_desc, $prod_img);
if ($addproduct_result == true) {
echo "Added Successfully";
} else {
echo "Failed";
}
}
}
}
Then I tried by adding following instead of normal tags.
<?php
$this->load->helper('form');
?>
<?php
echo form_open_multipart(base_url().'index.php/addproduct_controller');
?>
where it gaves me an error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/addproduct_controller.php
Line Number: 53
Please help me with this or show me where I have done the mistake.
enctype attribute missing in your from tag.
Add enctype="multipart/form-data" in your form tag
OR
In CI, Use form_open_multipart function to generate form tag
As per discussion in comment, update your code as below.
$data = array(
'upload_data' => $this->upload->data()
);
$prod_img = $data["upload_data"]->file_name;
You have missed out to include form attribute to upload the file
Add enctype="multipart/form-data" in your form tag
You have make the html form but not added file upload tag in your form creation.
add: enctype="multipart/form-data" in your form tag.
<form action="<?php echo base_url();?>index.php/addproduct_controller" method="post" enctype="multipart/form-data" >