CI4 Inserting ID from selected Strings - php

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.

Related

Codeigniter (Inserting category data into table)

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.

Can not save data to Database cakephp

I have table SubjectTutor who has column id, subject_id, tutor_id, province_id, city_id, school_id, state_private and status. I want to insert data into SubjectTutor table but the error is
province_id, city_id, school_id and state_private will not
saved into table SubjectTutor, but id, subject_id, and tutor_id
will be saved.
this is controller. I also set province_id, city_id, school_id and state_private value.
public function admin_add_pack($standard_id=null)
{
$this->loadModel('Plan');
$this->loadModel('SubjectTutor');
$this->loadModel('Standard');
$this->loadModel('Province');
$this->loadModel('City');
$this->loadModel('School');
$this->loadModel('User');
$standard_data = $this->Standard->find('first',array('conditions'=>array('Standard.id'=>$standard_id)));
$province_id = 32;
$city_id = 44;
$school_id = 1855;
$this->set('title_for_layout','Subject');
if(!empty($this->request->data))
{
if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
{
$blackHoleCallback = $this->Security->blackHoleCallback;
$this->$blackHoleCallback();
}
//validate user data
$this->SubjectTutor->set($this->request->data['SubjectTutor']);
$this->SubjectTutor->setValidation('add');
if ($this->SubjectTutor->validates())
{
// $this->request->data['Subject']['user_id'] = $this->Auth->user('id');
$userdata = $this->request->data['SubjectTutor'];
$this->SubjectTutor->save($userdata,false);
$subject_tutor_id = $this->SubjectTutor->id;
$this->SubjectTutor->school_id = 1855;
$this->SubjectTutor->province_id = 32;
$this->SubjectTutor->city_id = 44;
$this->SubjectTutor->state_private = 1;
$this->Session->setFlash("Record has been added successfully", 'admin_flash_good');
$this->redirect(array('controller'=>'standards', 'action'=>'subject_list',$standard_id));
}
else
{
$this->Session->setFlash("Record has not been created", 'admin_flash_bad');
}
}
$tutors = $this->User->getStandardTutorList($standard_id);
$subjects = $this->Subject->getStandardSubjectList($standard_id);
$standards = $this->Standard->getStandardList();
$provinces = $this->Province->getProvinceList();
$cities = $this->City->getCityList();
$schools = $this->School->getSchoolList();
$this->set(compact('provinces'));
$this->set(compact('standards','standard_id','province_id','city_id','school_id','standard_data','tutors','subjects','provinces','cities','schools','tutor_id'));
}
this is ctp file:
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1"> Select Tutor </label>
<?php echo($this->Form->input('SubjectTutor.tutor_id', array('options'=>$tutors,'div'=>false, 'label'=>false, "class" => "form-control",'empty'=>'Select Tutor')));?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1"> Select Standard </label>
<?php echo ($this->Form->input('Subject.standard_id2', array('options'=>$standards,"div"=>false,"default"=>$standard_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">Select Subject </label>
<?php echo ($this->Form->input("SubjectTutor.subject_id", array('empty'=>'--Select Subject--', 'options'=>$subjects,"div"=>false,"label"=>false,"class"=>"form-control",'disabled'=>false))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">Province </label>
<?php echo ($this->Form->input("SubjectTutor.province_id", array('empty'=>'--Select Province--', 'options'=>$provinces,"div"=>false,"default"=>$province_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">City </label>
<?php echo ($this->Form->input("SubjectTutor.city_id", array('empty'=>'--Select City--', 'options'=>$cities,"div"=>false,"default"=>$city_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="exampleInputPassword1">School </label>
<?php echo ($this->Form->input("SubjectTutor.school_id", array('empty'=>'--Select School--', 'options'=>$schools,"div"=>false,"default"=>$school_id,"label"=>false,"class"=>"form-control",'disabled'=>true))); ?>
</div>
</div>
When you use the 'disabled' option for a field in a view, that field doesn't get set when the form data is saved.. Either use 'readonly' option instead, or set those values in the controller before you save (since you don't need user input anyway). Or display the value to the user without pretending they have any input, and use hidden fields to pass the correct data.

Unable to fetch data from database in codeigniter php

Once the user login into site unable to fetch the data from database getting blank page if i write foreach condition here is my code.Fetching username and login verification is workig fine.
Controller:
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
}
else{
$this->load->view('welcome');
}
}
Model:
function getprofiledata($id)
{
$this->db->select('profile_details.*');
$this->db->from('profile_details');
$this->db->where(array('profile_details.profile_id'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<?php if(isset($records) && is_array($records) && count($records)>0): ?>
<?php foreach($records as $r):?>
<form action="<?php echo base_url();?>profile/updateprofile" role="form" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<?php
echo form_hidden('profile_id',$r->profile_id);
?>
<div class="form-group">
<label class="control-label col-sm-2 " for="name">Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="name" placeholder="Enter name" value="<?php echo $r->first_name;?>" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="profilename">Profile Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="profile_name" placeholder="Enter Profile name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="designation">Designation:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="designation" placeholder="Enter Designation">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<?php endforeach;endif;?>
You chose the wrong segment number on line $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));.
Take notice that segment counting starts with zero, so segment no 3 is actually the 4th one in the uri.
If you keep the user id inside your session, you should replace $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3)); with $records = $this->profile_model->getprofiledata($this->session->userdata('profile_id'))‌​‌​‌​;. And you're done.
add a new session when you login process like bellow in your login model :
<?php
public function login_user($user_name = '', $password=''){
$userdetails = array(
'email' => $user_name,
'password' => md5($password),
'status'=>1,
);
$this->db->where($userdetails);
$query = $this->db->get('profile_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'profile_id' => $user[0]->profile_id, // add new session profile_id
'first_name' => $user[0]->first_name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
?>
And some change your index method like bellow :
<?php
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['country'] = $this->signup_model->getcountry();
$data['states'] = $this->profile_model->getstates();
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id)‌​‌​;
$data['records']= $records;
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
$this->load->view('templates/sidebar',$data);
}
else{
$this->load->view('welcome');
}
}
?>
I have added new 3 line because i thinks you are no getting profile id properly in $this->uri->segment(3)
So,
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id)‌​‌​;
$data['records']= $records;

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

Codeigniter: not working on displaying form_error with set_value in form_dropdown for validation

I need to display the form_error with set_value in form_dropdown for validation and it didn't work for me.
Here's the model (model_home.php):
public function get_dropdown() {
$result = $this->db->select('designation_id, designation')->get('designation')->result_array();
$dropdown = array();
foreach($result as $r) {
$dropdown[$r['designation_id']] = $r['designation'];
}
return $dropdown;
}
Here's the controller (home.php):
public function viewAddEmployeeForm() {
$this->load->model('Model_home');
$data = array();
$data['dropdown'] = $this->Model_home->get_dropdown();
$this->load->view('imports/header');
$this->load->view('imports/menu');
$this->load->view('emp_add', $data);
}
public function saveEmployee() {
$this->load->model('Model_home');
$data = array();
$data['dropdown'] = $this->Model_home->get_dropdown();
$rules = array(
array('field'=>'emp_desig','label'=>'Designation','rules'=>'trim|required')
);
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == FALSE) {
$this->load->view('emp_add', $data);
} else {
$this->load->model('Model_home');
$p = new Model_home();
$p->designation_id = $this->input->post('emp_desi');
if($p->designation_id == 1) {
$p->user_type = 0;
} else {
$p->user_type = 1;
}
$result = $p->saveEmployee();
if (!$result) {
echo mysqli_error($result);
}
else {
redirect('home/goSettings', 'refresh');
}
}
}
Here's the view (emp_add.php):
<?php echo form_open('home/saveEmployee',array('class'=>'form-horizontal'));?>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Designation <span class="required"><font size="3" color="red">*</font></span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<?php echo form_dropdown('emp_desi', $dropdown, '', 'class="form-control" id="emp_desi" name="emp_desig" value="<?php echo set_value('emp_desig') ?>"'); ?>
<span style="color: red;"><?php echo form_error('emp_desig'); ?></span>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-success" name="emp_submit" id="emp_submit">Submit</button>
</div>
</div>
</form>
How will I display the form_error in form_dropdown especially for set_value? Thanks for your time.
Read the Form Helper doc. Your form_dropdown() was used incorrectly. You should pass in an array of options as the third parameter, rather than use set_value().

Categories