Codeigniter (Inserting category data into table) - php

I am new to CodeIgniter, I carried out an e-commerce project left by the former developer. The case is that the category data is not inserting into my table.
The code is very long in both controller and model but I cut it out and posted only the necessary part of it.
This is my controller.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Category extends Admin_Controller {
public function create()
{
/* Breadcrumbs */
$this->breadcrumbs->unshift(2, "New Category" , 'admin/category/create');
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
/* Validate form input */
$this->form_validation->set_rules('cat_name', 'Category Name', 'trim|required');
if ($this->form_validation->run() == TRUE)
{
$config['upload_path'] = './assets/uploads/category/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'png,jpeg';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "icon";
if ( ! $this->upload->do_upload($img))
{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/category');
}
else
{
$data=$this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/category/'.$file['file_name'];
$data = array(
'category_name' => $this->input->post('cat_name'),
'category_photo' => $photo,
'category_description' => $this->input->post('cat_desc')
);
$this->category_model->insertcategory($data);
//$this->ion_auth->messages()
$this->session->set_flashdata('message', "Successfully inserted!");
redirect('admin/category', 'refresh');
}
}
else
{
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->template->admin_render('admin/category/create', $this->data);
}
}
This is my model.
class Category_model extends CI_Model
{
function insertcategory($data) {
$query = $this->db->insert('category', $data);
if ($query) {
return true;
} else {
return false;
}
}
This is my form.
<div class="box-body">
<span style="color:red"><?php echo $message;?></span>
<?php echo form_open_multipart(current_url(), array('class' => 'form-horizontal', 'id' => 'form-create_user')); ?>
<div class="form-group">
<span class="col-sm-2 control-label">Category Name</span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cat_name" placeholder="Category Name" name="cat_name" required>
</div>
</div>
<div class="form-group">
<span class="col-sm-2 control-label">Category Description</span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cat_desc" placeholder="Description" name="cat_desc" >
</div>
</div>
<div class="form-group">
<span class="col-sm-2 control-label">Category Icon</span>
<div class="col-sm-10">
<input class="input-file uniform_on" id="icon" name="icon" type="file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn-group">
<?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-primary btn-flat', 'content' => lang('actions_submit'))); ?>
<?php echo form_button(array('type' => 'reset', 'class' => 'btn btn-warning btn-flat', 'content' => lang('actions_reset'))); ?>
<?php echo anchor('admin/category', lang('actions_cancel'), array('class' => 'btn btn-default btn-flat')); ?>
</div>
</div>
</div>
<?php echo form_close();?>
</div>

Could you please replace $img = "icon"; with $img = $this->input->post('icon');
Please check with the above data.
Also please post the error message you are getting.

Related

CI4 Inserting ID from selected Strings

I'm so tired of thinking how to solve this case. already search by internet and never solved.
straight to the point
this is my Controller of Product.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\Model_product;
use App\Models\Model_category;
use App\Models\Model_status;
use App\Models\Model_supplier;
class Product extends Controller
{
protected $helpers = [];
public function __construct()
{
helper(['form']);
$this->model_category = new Model_category();
$this->model_product = new Model_product();
$this->model_status = new Model_status();
$this->model_supplier = new Model_supplier();
}
public function index()
{
$data['tbproduct'] = $this->model_product->getProduct();
return view('product/index', $data);
}
public function create()
{
$all = [
'tbproduct' => $this->model_product->getProduct(),
'tbcategory' => $this->model_category->getCategory(),
'tbstatus' => $this->model_status->getStatus(),
'tbsupplier' => $this->model_supplier->getSupplier()
];
return view('product/create', $all);
}
public function store()
{
$validation = \Config\Services::validation();
$data = array(
'prod_name' => $this->request->getPost('prod_name'),
'prodcat_id' => $this->request->getGet('cat_id'),
'prod_serial' => $this->request->getPost('prod_serial'),
'prod_barcode' => $this->request->getPost('prod_barcode'),
'prodstat_id' => $this->request->getPost('stat_id'),
'prodsup_id' => $this->request->getPost('sup_id'),
'prod_image' => $this->request->getPost('prod_image')
);
if ($validation->run($data, 'product') == FALSE) {
session()->setFlashdata('inputs', $this->request->getPost());
session()->setFlashdata('errors', $validation->getErrors());
return redirect()->to(base_url('product/create'));
} else {
$model = new Model_product();
$simpan = $model->insertProduct($data);
if ($simpan) {
session()->setFlashdata('Success', 'Product has been created');
return redirect()->to(base_url('product'));
}
}
}
}
this is my Models Model_product.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class Model_product extends Model
{
protected $table = 'tbproduct';
public function getProduct($id = false)
{
if ($id === false) {
return $this->table('tbproducts')
->join('tbcategory', 'tbproduct.prodcat_id = tbcategory.cat_id', 'left')
->join('tbstatus', 'tbproduct.prodstat_id = tbstatus.stat_id', 'left')
->join('tbsupplier', 'tbproduct.prodsup_id = tbsupplier.sup_id', 'left')
->get()
->getResultArray();
} else {
return $this->table('tbproducts')
->join('tbcategory', 'tbproduct.prodcat_id = tbcategory.cat_id', 'left')
->join('tbstatus', 'tbproduct.prodstat_id = tbstatus.stat_id', 'left')
->join('tbsupplier', 'tbproduct.prodsup_id = tbsupplier.sup_id', 'left')
->where('tbproduct.prod_id', $id)
->get()
->getRowArray();
}
}
public function insertProduct($data)
{
return $this->db->table($this->table)->insert($data);
}
public function updateProduct($data, $id)
{
return $this->db->table($this->table)->update($data, ['prod_id' => $id]);
}
public function deleteProduct($id)
{
return $this->db->table($this->table)->delete(['prod_id' => $id]);
}
}
and this is my Views create.php
<?php echo view('_partials/header'); ?>
<?php echo view('_partials/sidebar'); ?>
<div class="content-wrapper">
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Create New Product</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Create New Product</li>
</ol>
</div>
</div>
</div>
</div>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<form action="<?php echo base_url('product/store'); ?>" method="post">
<div class="card">
<div class="card-body">
<?php
$inputs = session()->getFlashdata('inputs');
//$inputs_cat = isset($inputs['cat_id']) == null ? '' : $inputs['cat_id'];
$errors = session()->getFlashdata('errors');
if (!empty($errors)) { ?>
<div class="alert alert-danger" role="alert">
Whoops! There is something wrong, that is:
<ul>
<?php foreach ($errors as $error) : ?>
<li><?= esc($error) ?></li>
<?php endforeach ?>
</ul>
</div>
<?php } ?>
<div class="form-group">
<label for="">Product Name</label>
<input type="text" class="form-control" name="prod_name" placeholder="Enter product name" value="<?php echo isset($inputs['prod_name']); ?>">
</div>
<div class="form-row">
<div class="col mb-3">
<label for="">Category</label>
<select class="form-control" name="cat_name" id="cat_name">
<?php foreach ($tbcategory as $row) {
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
} ?>
</select>
</div>
<div class="col mb-3">
<label for="">Serial Number</label>
<input type="text" class="form-control" name="prod_serial" placeholder="Enter product serial number" value="<?php echo isset($inputs['prod_serial']); ?>">
</div>
<div class="col mb-3">
<label for="">Barcode</label>
<input type="text" class="form-control" name="prod_barcode" placeholder="Enter product barcode" value="<?php echo isset($inputs['prod_barcode']); ?>">
</div>
</div>
<div class="form-row">
<div class="col mb-3">
<label for="">Status</label>
<select class="form-control" name="stat_name" id="stat_name">
<?php foreach ($tbstatus as $row) {
echo '<option value="' . $row['stat_id'] . '">' . $row['stat_name'] . '</option>';
} ?>
</select>
</div>
<div class="col mb-3">
<label for="">Supplier</label>
<select class="form-control" name="sup_name" id="sup_name">
<?php foreach ($tbsupplier as $row) {
echo '<option value="' . $row['sup_id'] . '">' . $row['sup_name'] . '</option>';
} ?>
</select>
</div>
</div>
</div>
<div class="card-footer">
Back
<button type="submit" class="btn btn-primary float-right">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<?php echo view('_partials/footer'); ?>
i want to insert new data from Controller Product function store.
i've this problem, i cannot change string value into integer value for this
$data = array(
'prod_name' => $this->request->getPost('prod_name'),
'prodcat_id' => $this->request->getGet('cat_id'), ---->>> this is the problem
'prod_serial' => $this->request->getPost('prod_serial'),
'prod_barcode' => $this->request->getPost('prod_barcode'),
'prodstat_id' => $this->request->getPost('stat_id'), ---->>> and this
'prodsup_id' => $this->request->getPost('sup_id'), ---->>> and also this
'prod_image' => $this->request->getPost('prod_image')
);
if you see in the create.php Views, there is $row['***_id'] for all three tables.
and i want to grab that three ids into store.
and this is the Error shown:
mysqli_sql_exception #1048
Column 'prodcat_id' cannot be null
Your problem is that you are sending the cat_name field not the cat_id field from the form. Fix the names of the fields and will works.
The below will works
<?php
$data = array (
'prod_name' => $this->request->getPost('prod_name'),
'prodcat_id' => $this->request->getPost('cat_name'), // ---->>> name fixed **
'prod_serial' => $this->request->getPost('prod_serial'),
'prod_barcode' => $this->request->getPost('prod_barcode'),
'prodstat_id' => $this->request->getPost('stat_name'), // ---->>> and this **
'prodsup_id' => $this->request->getPost('sup_name'), // ---->>> and also this**
'prod_image' => $this->request->getPost('prod_image'),
);
Update:
Since this appears to be simple, but really this could be deceitful, i recommend the next steps to solve it:
Ensures that the form field names match with the named used on the php script
Ensure that you are sending data to the server. You can check the super globals. Something like print_r($_POST) is enough.
Ensure collect the data from the right source: get or post
In this case, the error comes from mysql. To mitigate this you can:
sets default values on columns if required
fill $data array conditionally. If there are no a cat_id, don't put an index 'cat_id' without value (or null)
thank you for helping me before.
i found the answer.
here is the correct code where i can get the cat_id, stat_id and sup_id.
in the View create.php
change this code
<select class="form-control" name="cat_name" id="cat_name">
into this
<select class="form-control" name="cat_id" id="cat_id">
this mean you will get the cat_id value from the database, instead of cat_name.
change the stat_name into stat_id, then sup_name into sup_id.
when all of that changed, you can insert the database with the correct id number when you selected the value from the dropdown box.
this is the answer of my problem, thank you for helping me.

Failed Upload Files Codeigniter

I'm try to make crud with upload file but somehow it's keep return FALSE but i don't know what's wwrong with my code if i var_dump($data) before condition upload it's show the name of my image but if i var_dump($uploads) it's keep show false
This is my controller
public function saveReimburse()
{
validate_submitted_data(array(
'nama' => 'required',
'category_reimburse_id' => 'required',
'amount' => 'required|numeric',
'date_reimburse' => 'required',
));
// data
$data = [
'nama' => $this->input->post('nama'),
'category_reimburse_id' => $this->input->post('category_reimburse_id'),
'amount' => $this->input->post('amount'),
'date_reimburse' => $this->input->post('date_reimburse'),
'photo' => $_FILES['photo'],
];
// condition
$date = date('Y-m-d');
$date = strtotime($date);
$date = strtotime('-7 day', $date);
if ($data['date_reimburse'] < date('Y-m-d', $date)) {
echo json_encode(array('succes' => FALSE, 'message' => 'Max Reimburse was 1 week ago'));
} else {
if ($data['photo'] = "") {
} else {
$config = [
'upload_path' => './assets/reimburse',
'allowed_types' => 'jpg|png|gif',
'overwrite' => TRUE
];
$this->load->library('upload', $config);
$upload = $this->upload->do_upload('photo');
var_dump($upload);exit;
if (!$upload) {
json_encode(array('success' => FALSE, 'message' => 'Failed Upload'));
redirect('Reimburse/index', 'refresh');
} else {
$this->upload->data('file_name');
$save = $this->reimburseModel->saveReimburse('reimburse', $data);
var_dump($data);exit;
if (!$save) {
echo json_encode(array('success' => FALSE, 'message' => 'Failed to reccord'));
} else {
redirect('Reimburse/index', 'refresh');
echo json_encode(array('success' => TRUE, 'message' => 'Reimburse Success'));
}
}
}
}
}
and this my model
function saveReimburse($table,$data)
{
$this->load->database('default', TRUE);
if(!$this->db->insert($table,$data))
return FALSE;
$data["id"] = $this->db->insert_id();
return (object) $data;
}
This is my input code
<?php echo form_open_multipart(get_uri("Reimburses/saveReimburse"), array("id" => "formReimburse", "class" => "general-form", "role" => "form")); ?>
<div id="expense-dropzone" class="post-dropzone">
<div class="modal-body clearfix">
<!-- <form action =" " method='POST'> -->
<div class="form-group">
<label for="Nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" placeholder="Nama">
</div>
<div class="form-group">
<label for="category_reimburse_id">Category</label>
<select class="form-control form-control-lg" name="category_reimburse_id">
<option value ="">-</option>
<?php
foreach($category as $ct){?>
<option value ="<?php echo $ct->id ?>"><?php echo $ct->category ?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label for="amount">Amount</label>
<input type="text" class="form-control" id="amount" name="amount" placeholder="Amount">
</div>
<div class="form-group">
<label for="date_reimburse">Date</label>
<input type="date" class="form-control" id="date_reimburse" name="date_reimburse" value='<?php echo date('Y-m-d') ?>'>
</div>
<div class="form-group">
<div class="form-group">
<label for="photo">Input Photo</label>
<input type="file" class="form-control-file" id="photo" name ="photo">
</div>
</div>
<div class="float-right">
<button type="cancel" class="btn btn-warning ">Cancel</button>
<button type="submit" class="btn btn-primary ">Submit</button>
</div>
<!-- </form> -->
</div>
</div>
<?php echo form_close() ?>
Check the error using the error function
print_r($this->upload->display_errors());
Try adding bellow upload path
'upload_path' => '../assets/reimburse';
Put one / after reimburse like "./assets/reimburse/" can solve problem may be and assets folder in root directory

How can i add two image from two different inputs on single page in codeigniter

I am trying to upload two images in database at once submit attempt from single form that have two different file input fields.
I tried but its not working when i try to show result using print_r it gives a single file name for both input fields. How can i do it perfectly in codeigniter. please help for your reference i am uploading my code. you if any error please let me know.
HTML Form Code
<form id="form_edit" method="post" action="<?php echo base_url(" admin/aboutus/update/".$aboutus->id); ?>" enctype="multipart/form-data" accept-charset="utf-8">
<div class="form-group row">
<div class="col-md-4 col-xs-4">
<input type="text" name="imgtitle" title="About Us Image Title" class="form-control input-sm" value="<?php echo set_value('imgtitle', $aboutus->imgtitle); ?>" placeholder="Image Title" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'imgdetail','title'=>'About Us Image Description','class'=>'form-control mptop input-sm','required'=>'required','value'=> set_value('detail', $aboutus->imgdetail)]); ?>
<input type="file" name="img" title="About Us Image" class="form-control input-sm">
</div>
<div class="col-md-4 col-xs-4">
<input type="text" title="About Us Title" class="form-control input-sm" name="title" value="<?php echo set_value('title', $aboutus->title); ?>" placeholder="Type left side title of about us of maximum 15 characters" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'detail','title'=>"About Us Detail",'class'=>'form-control mptop input-sm mptop','required'=>'required','value'=> set_value('detail', $aboutus->detail)]); ?>
</div>
<div class="col-md-4 col-xs-4">
<input type="text" name="img_2title" title="About Us Image Title" class="form-control input-sm" value="<?php echo set_value('imgtitle', $aboutus->img_2title); ?>" placeholder="Image Title" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'img_2detail','title'=>'About Us Image Description','class'=>'form-control mptop input-sm','required'=>'required','value'=> set_value('detail', $aboutus->img_2detail)]); ?>
<input type="file" name="img_2" title="About Us Image" class="form-control input-sm">
<!-- id="detail" -->
</div>
</div>
<div class="form-group row">
<div class="col-md-12 col-xs-12 mptop rmzero rpZero">
<div class="btn-group pull-right text-right">
<i class="fa fa-arrow-left"></i> Back
<!-- <i class="fa fa-search"></i> Preview -->
<button type="submit" class="btn btn-success btn-sm" name="submit" id="save"><i class="fa fa-save"></i> Save</button>
</div>
</div>
</div>
</form>
My Codeigniter Control Code
public function update($id)
{
$res = array();
//form field validation rules
$this->form_validation->set_rules('title', 'Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('detail', 'Detail', 'required|max_length[2000]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('imgtitle', 'Image Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('imgdetail', 'Image Description', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('img_2title', 'Second Image Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('img_2detail', 'Second Image Description', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$config['upload_path'] = 'fassets/images/aboutus';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
//$config['file_name'] = $_FILES['img']['name'];
$config['overwrite'] = TRUE;
//Load upload library and initialize configuration
$this->load->library('upload', $config);
// echo $image_path; exit;
if((!$this->upload->do_upload('img')) && (!$this->upload->do_upload('img_2')))
{
$userData = array(
'title' => $this->input->post('title'),
'detail' => $this->input->post('detail'),
'imgtitle' => $this->input->post('imgtitle'),
'imgdetail' => $this->input->post('imgdetail'),
'img_2title' => $this->input->post('img_2title'),
'img_2detail' => $this->input->post('img_2detail')
);
//Pass user data to model
$insertUserData = $this->AboutusModel->update($userData, $id);
}
else
{
$userData = array(
'title' => $this->input->post('title'),
'detail' => $this->input->post('detail'),
'imgtitle' => $this->input->post('imgtitle'),
'imgdetail' => $this->input->post('imgdetail'),
'img_2title' => $this->input->post('img_2title'),
'img_2detail' => $this->input->post('img_2detail'),
'img' => $this->upload->data('file_name'),
'img_2' => $this->upload->data('file_name')
);
echo "<pre>";
print_r($userData);
exit;
//Pass user data to model
$insertUserData = $this->AboutusModel->update($userData, $id);
}
//Storing insertion status message.
if($insertUserData){
$res = array(
'mes' => 'text-success',
'msg' => "Record has been saved successfully.",
);
echo json_encode($res);
} else {
$res = array(
'mes' => 'text-danger',
'msg' => "Oops! Something went wrong.",
);
echo json_encode($res);
}
}
With $this->upload->data('file_name'), you are getting only the last uploaded file name. You're missing the first one. To solve this simple issue, store both filenames in variables to use after both files have successfully been uploaded.
Before:
$this->load->library('upload', $config);
Add:
$img1 = $_FILES['img']['name'];
$img2 = $_FILES['img_2']['name'];
Replace:
'img' => $this->upload->data('file_name'),
'img_2' => $this->upload->data('file_name')
With:
'img' => $img1,
'img_2' => $img2
Another Issue:
In your current code, if your first upload succeeds the second will fail. To prevent that.
Replace:
if((!$this->upload->do_upload('img')) && (!$this->upload->do_upload('img_2')))
With:
$upload1_ok = $this->upload->do_upload('img');
$upload2_ok = $this->upload->do_upload('img_2');
if($upload1_ok == false && $upload2_ok == false)

Problems on uploading image files

This is my view file where form for image and other data exists:
<?php echo form_open_multipart('Login/client_profile'); ?>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" name="company_name" >
</div>
<div class="form-group">
<label>Upload Profile Picture</label>
<input type="file" name="profile_pic" accept="image/*" class="form-control" required>
</div>
<div class="form-group">
<label>Mobile Number</label>
<input type="number" class="form-control" name="mobile" required>
</div>
<div class="form-group">
<label>Specialist in</label>
<input type="text" class="form-control" name="specialist_in" >
</div>
<div class="form-group">
<label>Position</label>
<input type="text" class="form-control" name="position" >
</div>
<?php
$data7 = array(
'type' => 'submit',
'value' => 'Update',
'class' => 'btn btn-primary ',
);
echo form_submit($data7);
echo form_close();
?>
This is the controller file Client.php
public function client_profile()
{
$client=$this->input->post();
$client['profile_pic']=$this->input->post('profile_pic');
$this->load->model('Clientmodel');
$email=$this->session->userdata('email_id');
$this->Clientmodel->add_client_details($email,$client);
$ppic['pic']=$this->Clientmodel->get_pic($email);
$config['upload_path'] = './profile/';
$config['allowed_types'] = 'jpg|jif|png|jpeg';
$this->load->library('upload', $config);
$field = 'pic';
if ($this->upload->do_upload($field)) {
$temp = $this->upload->data();
$pic = $temp['file_name'];
}
$this->load->view('client/pro_header',$ppic);
$this->load->view('client/client_dashboard',$client);
}
This is model file Clientmodel.php
public function add_client_details($email, Array $client)
{
return $this->db->where(['email'=>$email])
->update('clients',$client);
}
public function get_pic($login_email)
{
$q=$this->db->where(['email'=>$login_email])
->get('clients');
return $q->row()->profile_pic;
}
After entering all the data all the fields other than image can be fetched using $this->input->post when i try to fetch 'profile_pic' it returns nothing.And the image file name is also not inserted in database.Field 'profile_pic' is there in table 'clients'
This is the for uploading it's not checking any validation
public function upload_docs () {
if($this->input->post('action') == 'Upload') {
$company_name = $input->post('company_name');
$position = $input->post('position');
$mobile = $input->post('mobile');
$specialist_in = $input->post('specialist_in');
// capture all your variable like this
$file_path = './assets/images/uploads';
if ($_FILES["profile_pic"]["error"] > 0) {
$data['msg'] = 'your message';
} else {
if(!is_dir($file_path)) #mkdir($file_path, 0777, true);
if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $file_path.'/'.$_FILES['profile_pic']['name'])) {
$upload_data = array('company_name'=> $company_name,'mobile'=> $mobile,'specialist_in'=> $specialist_in,'profile_pic' => $_FILES['profile_pic']['name']);
$insert_id = $this->Your_model->addRecord($upload_data);
if ($insert_id) {
// redirect('admin/index','refresh');
}
}
}
}
$data['title'] = 'upload';
$this->load->view('admin/upload',$data);
}

Codeigniter: redirect page to user profile after update

I want to show an updated profile page of users on my site. The update on database is actually working but i want my userprofile page to show the updated datas once it clicked the submit button. What will I add here D:
MemberLoginController.php (controller)
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class MemberLoginController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('MemberLoginModel');
}
public function home(){
$this->load->view('pages/index');
}
public function userprofile(){
$this->load->view('member/userprofile');
}
public function useredit(){
$this->load->view('member/useredit');
}
public function memberlogin(){
$this->form_validation->set_error_delimiters('<p class=error>','</p>');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run()){
// Perform Actions after getting valid form inputs
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('index.php/MemberLoginController/members');
}else
$this->load->view('pages/index');
}
public function members(){
if($this->session->userdata('is_logged_in')){
$vis = "hidden";
$id = $this->session->userdata('id');
$this->load->model('MemberLoginModel');
$memberinfo['memberinfo']=$this->MemberLoginModel->getMember($id);
$this->load->view('member/userprofile',$memberinfo);
}else{
redirect('index.php/HomeController/home');
}
}
public function edit($id){
$data = array(
"action" => base_url('/index.php/MemberLoginController/update/'.$id),
"data" => $this->db->get_where('member',array('id'=>$id))
);
$this->load->view('member/useredit', $data);
}
public function update($id){
$data = array(
'memberfname'=> $this->input->post('memberfname'),
'memberlname'=> $this->input->post('memberlname'),
'email'=>$this->input->post('email'),
);
$this->db->update('member',$data,array('id'=> $id));
redirect('index.php/MemberLoginController/getMember/'.$id);
}
public function getMember(){
$this->load->model('MemberLoginModel');
$memberinfo['memberinfo']=$this->MemberLoginModel->getMember();
$this->load->view('member/userprofile',$memberinfo);
}
public function validate_credentials(){
$this->load->model('MemberLoginModel');
if($this->MemberLoginModel->login()){
echo ("<SCRIPT LANGUAGE = 'JavaScript'>
window.alert('Login Successfully')
window.location.href='userprofile'
</SCRIPT>");
exit();
return true;
}else{
echo ("<SCRIPT LANGUAGE = 'JavaScript'>
window.alert('Invalid username or password. Please click LOGIN again.')
window.location.href='home'
</SCRIPT>");
exit();
//$this->form_validation- >set_message('validate_credentials','Incorrect Email/Password');
return false;
}
}
}
?>
MemberLoginModel.php
<?php class MemberLoginModel extends CI_Model{
public function __construct()
{
parent::__construct();
}
function login()
{
$this->db->where('email',$this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('member'); /*i added 'member' table on db new members*/
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'id' => $rows->id,
'memberfname' => $rows->memberfname,
'memberlname' => $rows->memberlname,
'email' => $rows->email,
'logged_in' => TRUE
);
}
$this->session->set_userdata($newdata);
return true;
}else{
return false;
}
}
public function add_user()
{
$data = array(
'memberfname'=>$this->input->post('memberfname'),
'memberlname'=>$this->input->post('memberlname'),
'email'=>$this->input->post('email'),
'password'=>md5($this->input->post('password')),
);
$this->db->insert('member',$data);
}
public function getMember()
{
$query=$this->db->get('member');
return $query->result();
}
}
?>
Userprofile.php (view)
<body>
<div class="row rowpadding">
<div class="col-md-3 col-sm-3">
<div class="user-wrapper">
<div class="description">
<img height="200px" width="200px" src="<?php echo base_url();?>upload/no-avatar.jpg">
</div>
<br><br>
</div>
</div>
<div class="col-md-6 col-sm-6 user-wrapper">
<div class="description">
<br>
<h2 class="name">Hi, <?php echo $this->session->userdata('memberfname'); ?>!</h2>
<hr/>
<div class="colwrapper">
<div class="cont-5">
<div class="cont-6 name"><p class="para-2"><span class="font-3">First Name: <?php echo $this->session->userdata('memberfname'); ?>
</span></p></div>
</div><br>
<div class="cont-7">
<div class="cont-8 name"><p class="para-3"><span class="font-4">Last Name: <?php echo $this->session->userdata('memberlname'); ?></span></p></div>
</div><br>
<div class="cont-9">
<div class="cont-10"><p class="para-4"><span class="font-5">Email Address: <?php echo $this->session->userdata('email'); ?></span></p></div>
</div><br>
<div class="cont-11">
<div class="cont-12"><p class="para-5"><span class="font-6"></span></p></div>
</div><br>
</div>
<br><br>
</div>
</div>
<div class="col-md-3 col-sm-3 user-wrapper">
<div class="user-wrapper">
<br>
<div class="description">
<ul class="rightnavi"style="">
<li class="rightnavi">Add Profile Photo</li>
<li class="rightnavi">Update Your Profile</li>
</ul>
<hr/>
</div>
</div>
</div>
<!-- USER PROFILE ROW END-->
</div>
</body>
Useredit.php (View)
<form action="<?php echo $action;?>" method="POST" enctype="multipart/form-data">
<div class="container">
<div class="row rowpadding">
<div class="col-md-3 col-sm-3">
<div class="user-wrapper">
<div class="description">
<img height="200px" width="200px" src="<?php echo base_url();?>upload/no-avatar.jpg">
</div>
<br><br>
</div>
</div>
<div class="col-md-6 col-sm-6 user-wrapper">
<div class="description">
<br>
<h2 class="name">Hi, <?php echo $this->session->userdata('memberfname'); ?>!</h2>
<hr />
<p>
<div class="colwrapper">
<div class="cont-5">
<div class="cont-6 name"><p class="para-2"><span class="font-3">First Name:
<input type="text" name="memberfname" value="<?php echo $this->session->userdata('memberfname'); ?>" required />
</span></p></div>
</div><br>
<div class="cont-7">
<div class="cont-8 name"><p class="para-3"><span class="font-4">Last Name:
<input type="text" name="memberlname" value="<?php echo $this->session->userdata('memberlname'); ?>" required /></span></p></div>
</div><br>
<div class="cont-9">
<div class="cont-10"><p class="para-4"><span class="font-5">Email Address:
<input type="text" name="email" value="<?php echo $this->session->userdata('email'); ?>" required /></span></p></div>
</div><br>
<div class="cont-11">
<div>
<input type="hidden" name="hidden" value="<?php echo $this->session->userdata('id'); ?>"/>
<input type="submit" value="update">
</div>
</div>
<br><br>
</p>
</div>
</div>
</div>
</div>
</div>
</form>
You should combine form_validation object with your code.
public function update($id)
{
if ( (int)$id < 1)//$id is not an integer
{
redirect('memberlogincontroller/home', 'refresh');
}
else
{
$this->load->library('form_validation');//it's good to autoload it
$this->form_validation->set_rules('memberfname', 'First Name', 'trim|required');
$this->form_validation->set_rules('memberlname', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required');
if ($this->validation_form->run() === FALSE)
{
$this->load->view('userprofile');
}
else
{
$data = array(
'memberfname' => $this->input->post('memberfname'),
'memberlname' => $this->input->post('memberlname'),
'email' => $this->input->post('email'),
);
$this->db->update('member',$data,array('id'=> $id));
redirect('memberlogincontroller/getMember/' . $id, 'refresh');
}
}
}
In model you are not passing id of specific member. It should be like this
public function getMember($id)
{
$this->db->where('id', $id);
$query = $this->db->get('member');
if ($query->num_rows() !== 1)
{
return FALSE;
}
return $query->row();//since you need just single member data
}
Also, in controller method code you have to pass $id to model:
public function getMember($id)
{
if (int($id) < 1)
{
redirect('memberlogincontroller/home', 'refresh');//no valid uri segment
}
else
{
$this->load->model('MemberLoginModel');
$memberinfo['memberinfo'] = $this->MemberLoginModel->getMember($id);
if ( ! $memberinfo['memberinfo'])//returned FALSE from model
{
redirect('memberlogincontroller/home', 'refresh');//no $id in DB
}
else
{
$this->load->view('member/userprofile',$memberinfo);
}
}
}
Also, you should pay attention to naming convention. You shouldn't close file with closing php tag. My proposal is to read docs carefully since you could avoid lot of annoying bugs that way.
Redirect should be
redirect('MemberLoginController/members');
redirect('Controller/Method');
If method is not added, So it will call the index() method by default

Categories