My picture is not saved into my uploads/pictures folder - php

My Controller Codes
Looking forward for your help! thank you :
public function index()
{
$registration = $this->Registration_model->get_all();
$data = array(
'registration_data' => $registration
);
$this->load->view('registration/registration_list', $data);
}
public function do_upload()
{
$config['upload_path'] = './uploads/pictures/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000;
$config['max_width'] = 10240000;
$config['max_height'] = 76800000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('Image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('registration_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data['upload_data']['file_name'];
}
}
public function read($id)
{
$row = $this->Registration_model->get_by_id($id);
if ($row) {
$data = array(
'id' => $row->id,
'firstName' => $row->firstName,
'lastName' => $row->lastName,
'gender' => $row->gender,
'address' => $row->address,
'dob' => $row->dob,
'Image' => $row->Image,
);
$this->load->view('registration/registration_read', $data);
} else {
$this->session->set_flashdata('message', 'Record Not Found');
redirect(site_url('registration'));
}
}
public function create()
{
$data = array(
'button' => 'Create',
'action' => site_url('registration/create_action'),
'id' => set_value('id'),
'firstName' => set_value('firstName'),
'lastName' => set_value('lastName'),
'gender' => set_value('gender'),
'address' => set_value('address'),
'dob' => set_value('dob'),
'Image' =>set_value('image'),
);
$this->load->view('registration/registration_form', $data);
}
public function create_action()
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'firstName' => $this->input->post('firstName',TRUE),
'lastName' => $this->input->post('lastName',TRUE),
'gender' => $this->input->post('gender',TRUE),
'address' => $this->input->post('address',TRUE),
'dob' => $this->input->post('dob',TRUE),
'Image' => $this->input->post('Image',TRUE),
);
$this->Registration_model->insert($data);
$this->session->set_flashdata('message', 'The New Record was Successfuly Added');
redirect(site_url('registration'));
}
}
My Views Codes
<div class="form-group">
<label for="date">Dob <?php echo form_error('dob') ?></label>
<input type="text" class="form-control" name="dob" id="dob" placeholder="Dob" value="<?php echo $dob; ?>" />
</div>
<div class="form-group">
<label for="varchar">Image <?php echo form_open_multipart('upload/do_upload');?></label>
<input type="file" class="form-control" name="Image" id="Image" height="50" />
<br/>
</div>
<br/>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<button type="submit" class="btn btn-primary"name="userSubmit"><?php echo $button ?></button>
My Model
class Registration_model extends CI_Model
{
public $table = 'registration';
public $id = 'id';
public $order = 'DESC';
function __construct()
{
parent::__construct();
}
// get all
function get_all()
{
$this->db->order_by($this->id, $this->order);
return $this->db->get($this->table)->result();
}
// get data by id
function get_by_id($id)
{
$this->db->where($this->id, $id);
return $this->db->get($this->table)->row();
}
// get total rows
function total_rows($q = NULL) {
$this->db->like('id', $q);
$this->db->or_like('firstName', $q);
$this->db->or_like('lastName', $q);
$this->db->or_like('gender', $q);
$this->db->or_like('address', $q);
$this->db->or_like('dob', $q);
$this->db->or_like('Image', $q);
$this->db->from($this->table);
return $this->db->count_all_results();
}
// get data with limit and search
function get_limit_data($limit, $start = 0, $q = NULL) {
$this->db->order_by($this->id, $this->order);
$this->db->like('id', $q);
$this->db->or_like('firstName', $q);
$this->db->or_like('lastName', $q);
$this->db->or_like('gender', $q);
$this->db->or_like('address', $q);
$this->db->or_like('dob', $q);
$this->db->or_like('Image', $q);
$this->db->limit($limit, $start);
return $this->db->get($this->table)->result();
}
// insert data
function insert($data)
{
$this->db->insert($this->table, $data);
}
// update data
function update($id, $data)
{
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
// delete data
function delete($id)
{
$this->db->where($this->id, $id);
$this->db->delete($this->table);
}
}

Hello You can try this
$config['upload_path'] = 'ADD HERE YOUR SITE PATH TO PICTURE'; // Like SITE_PATH .'/uploads/pictures/';
and print $config['upload_path'] and check it's correct your upload picture path

I've had the same issue before. Depending on your server, you may want to remove the ./ from your upload path.
public function do_upload()
{
$config['upload_path'] = 'uploads/pictures/';

Change your view as below. You are not closing form
<?php echo form_open_multipart('upload/do_upload');?>
<div class="form-group">
<label for="date">Dob <?php echo form_error('dob') ?></label>
input type="text" class="form-control" name="dob" id="dob" placeholder="Dob" value="<?php echo $dob; ?>" />
</div>
<div class="form-group">
<label for="varchar">Image </label>
<input type="file" class="form-control" name="Image" id="Image" height="50" />
<br/>
</div>
<br/>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<button type="submit" class="btn btn-primary"name="userSubmit"><?php echo $button ?></button>
<?= form_close()?>

Related

Codeigniter: Cannot upload files, Undefined Index : avatar

I cannot seem to upload files in codeigniter. I don't know if the issue lies with the if ($_FILES['avatar']['name'] == "").
My controller
private function upload_avatar($file)
{
$newName = $file->getRandomName();
$upload = $file->move(ROOTPATH . 'public/assets/avatar', $newName);
if ($upload) {
return $newName;
} else {
return false;
}
}
public function change_data()
{
helper(['form', 'url']);
$userModel = new UserModel();
if ($this->request->getMethod() == 'post') {
if ($_FILES['avatar']['name'] == "")
{
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]'
];
} else {
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]',
'avatar' => [
'uploaded[avatar]',
'mime_in[avatar,image/jpg,image/jpeg,image/png]',
'max_size[avatar,4096]'
]
];
}
if ($this->validate($rules)) {
if ($_FILES['avatar']['name'] == "") {
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
];
} else {
//get data user by session email
$user = $userModel->where('email', session()->get('email'))
->first();
if ($user) {
$deleteFile = unlink('./assets/avatar/' . $$user['avatar']);
if ($deleteFile) {
$file = $this->request->getFile('avatar');
$uploadFile = $this->upload_avatar($file);
}
}
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
'avatar' => $uploadFile,
];
}
$update = $userModel->update($user['id_user'], $params);
if ($update) {
session()->setFlashdata('success', 'Berhasil Update Data. Apabila Tampilan Data Belum Berubah, Silakan Lakukan Logout dan Login Kembali');
return redirect()->route('profile');
} else {
session()->setFlashdata('danger', 'Gagal Update Data');
return redirect()->route('edit')->withInput();
}
} else {
$data['validation'] = $this->validator;
}
}
$data['title'] = 'Edit Profile';
return view('admin/users/ubah_data', $data);
}
My view
<form action="<?= base_url('admin/user/change_data') ?>" method="POST">
<?= csrf_field(); ?>
<div class="form-group">
<label for="nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" value="<?= session()->nama ?>">
</div>
<div class="form-group">
<label for="nip">NIP</label>
<input type="text" class="form-control" id="nip" name="nip" value="<?= session()->nip ?>">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="<?= session()->email ?>">
</div>
<div class="form-group">
<label for="tempat_lahir">Tempat Lahir</label>
<input type="text" class="form-control" id="tempat_lahir" name="tempat_lahir" value="<?= session()->tempat_lahir ?>">
</div>
<div class="form-group">
<label for="avatar">Foto <small>(Optional)</small></label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="avatar" name="avatar">
<label class="custom-file-label" for="avatar">Choose file</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info" />
</div>
</form>
After i push the upload button Undefined index: avatar message appeared.
Any help will be greatly appreciated. I cannot seem to figure out why ($_FILES['avatar']['name'] == "") has problem
I think you miss to include enctype="multipart/form-data" in form tag
<form action="url-action" method="POST" enctype="multipart/form-data">
your form
</form>

How to update images with codeigniter

I have a problem when I want to update the image.
the update process went well, but the image cannot update.
Please help. Thanks.
Here is View :
<?php echo form_open('update'); ?>
<input type="hidden" name="id" value="<?php echo $data->id; ?>">
<input type="hidden" id="old" name="old" value="<?php echo $data->image;?>">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" value="<?php echo $data->name; ?>">
</div>
<div class="form-group">
<label>Change Image</label>
<input class="form-control" type="file" name="image">
</div>
<button type="submit" class="btn btn-default">Submit</button>
Here is Controller :
public function Update(){
$id = $this->input->post('id');
$name = $this->input->post('name');
if($_FILES['image']['name']!=""){
$config['upload_path'] = './image/';
$config['allowed_types'] ='gif|jpg|png|jpeg|';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('image')){
$error = array('error' => $this->upload->display_errors());
}else{
$upload_data=$this->upload->data();
$image_name =$upload_data['file_name'];
}
}else{
$image_name=$this->input->post('old');
}
$data = array( 'name' => $name, 'image' => $image_name, );
$this->model_user->update_user($data,$id);
}
Here is Model :
public function update_user($data, $id)
{
$this->db->where('id', $id);
$this->db->update('tabel_user', $data);
return TRUE;
}
you code dose not have any mistake. but you use some unwanted input.
try to debug your code.
in model
before return
public function update_user($data, $id)
{
$this->db->where('id', $id);
$this->db->update('tabel_user', $data);
echo $this->db->last_query();
echo "</br> id : ".$id;
print_r($data); EXIT;
}
if you get get query printed. check what you have missed. if you don't
at controller
after line $error = array('error' => $this->upload->display_errors());
put print_r($error); exit;
and may be you have forgotten to mention multi part at your view.
do these three things hope you will find what is wrong.
First, check your column names are same as array key values
Try These,
public function update_user($data, $id)
{
echo'<pre>';print_r($data);
$this->db->where('id', $id);
$flag = $this->db->update('tabel_user', $data);
echo $flag;die;
}
$flag will tell you True or False

Trying to get property of non-object CodeIgniter

I am new to CodeIgniter. I am using a form with Form Validation. My problem is when I press "Edit details", an ERROR appears. "Trying to get property of non-object".
This is my view: user/edit_user.php
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
<h1>EDIT YOUR DETAILS</h1>
<?php if (validation_errors()){ ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<form method="POST" action="<?=base_url().'user/do_edit_user'?>">
<input value="<?= $user->id ?>" name="id" type="hidden">
<input value="<?= $user->name ?>" type="text" name="name" class="form-control" placeholder="Name"> <br>
<input value="<?= $user->password ?>" type="password" name="password" class="form-control" placeholder="Password"> <br>
<input value="<?= $user->email ?>" type="text" name="email" class="form-control" placeholder="Email"> <br>
<input value="<?= $user->number ?>" type="number" name="number" class="form-control" placeholder="Number"> <br>
<input value="<?= $user->university ?>" type="text" name="university" class="form-control" placeholder="University"> <br>
<button class="btn btn-success" type="submit">Submit</button>
</form>
</div>
<div class="col-md-3">
</div>
This is my controller: User.php
public function edit_details(){
$id = $this->uri->segment(3);
$data['user'] = $this->AdminModel->getUser($id);
$this->load->view('includes/header');
$this->load->view('includes/navbar');
$this->load->view('users/edit_user', $data);
$this->load->view('includes/footer');
}
public function display(){
$cond = array (
'email' => $this->input->post('email'),
'password' => sha1($this->input->post('password'))
);
$data['user'] = $this->UserModel->getUser($cond);
if(!($data))
{
redirect('user/index');
}
else
{
$this->load->view('includes/header');
$this->load->view('includes/navbar');
$this->load->view('users/display', $data);
$this->load->view('includes/footer');
}
}
And my last controller for do_edit_user`
public function do_edit_user(){
$id = $this->input->post('id');
$user = array(
'name' => $this->input->post('name'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'number' => $this->input->post('number'),
'university' => $this->input->post('university')
);
$this->form_validation->set_rules('name', 'Name', 'required|min_length[3]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('number', 'Number', 'max_length[11]');
$this->form_validation->set_rules('university', 'University', 'min_length[8]');
if ($this->form_validation->run() == FALSE)
{
$this->edit_details();
}
else
{
$this->AdminModel->updateUser($id, $user);
redirect('user/display');
}
}
public function activate(){
$cond = array(
'activation_code' => $this->uri->segment(3)
);
if(!($this->UserModel->checkAccount($cond)==null)){
echo 'successfully registered email';
}else{
echo 'invalid';
}
}
What am I missing or need to change? Sorry for my format if this is wrong. Correct me if there was wrong in my post and code.
Actual Error is A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: users/edit_user.php
Line Number: 16
Line Number: 17
Line Number: 18
Line Number: 19
Line Number: 20
Line Number: 21
My UserModel
public function insertUser($user){
$this->db->insert('tbluser', $user);
}
public function checkAccount($cond){
$this->db->where($cond);
$this->db->update('tbluser', array('status'=>'active'));
$q = $this->db->get_where('tbluser', $cond);
return $q->row();
}
public function getUser($cond){
$this->db->where($cond);
$q = $this->db->get('tbluser');
return $q->row();
}
public function getUser($id){
$q = $this->db->get_where('tbluser', array('id' => $id));
return $q->row();
}
You should handle the null of $user object.
Following things are cheats and will not give you errors.
<?=#$user->id using a # sign if you are not sure about $user object
OR
Assign the user to a object variable.
$data['user'] = new stdClass();
$data['user'] = $this->UserModel->getUser($cond);
Maybe it's because you return a string or an array from UserModel->getUser() method, like return $query->result_array() or return $string, to $data['user'] in User controller instead of return $query->result(). Check it.
Update 1
I'm newbie too, but you can try this if you still need help:
User.php (change to)
$email => $this->input->post('email'); //this
$password => sha1($this->input->post('password')); //this
$data['user'] = $this->UserModel->getUser($email, $password); //or this
and your UserModel.php (change to)
public function getUser($email, $password){ // and this are
$this->db->where('email' => $email); // not a
$this->db->where('password' => $password); // nesessary changes but you can try it
$q = $this->db->get('tbluser');
return $q->result(); // try result() instead of row()
}
$user['id']
$user['name']
$user['password']
$user['email']
$user['number']
$user['university']
try to do like this when you return row_array() or result()

Registration form with image upload in Codeigniter

I have a user registration form and it's working fine but would like to add an image upload feature inside it. This is basically what I'd like to achieve
ScreenShot 1
ScreenShot 2
So far, this is what I have done
Controller:
class Employees extends CI_Controller {
var $pgToLoad;
public function __construct() {
parent::__construct();
#this will start the session
session_start();
$this->load->helper(array('form', 'url'));
if(!isset($_SESSION['userId']) || !isset($_SESSION['userLevel']) || !isset($_SESSION['employeeid']) || !isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])) {
redirect('home', 'location');
}
#this will load the model
$this->load->model('Contents');
#get last uri segment to determine which content to load
$continue = true;
$i = 0;
do {
$i++;
if ($this->uri->segment($i) != "") $this->pgToLoad = $this->uri->segment($i);
else $continue = false;
} while ($continue);
}
public function index() {
$this->main();
}
public function main() {
#set default content to load
$this->pgToLoad = empty($this->pgToLoad) ? "employees" : $this->pgToLoad;
$disMsg = "";
#this will delete the record selected
if($this->uri->segment(2) == 'delete') {
$this->deleteRecord();
}
#this will check if the post value is trigger
if(isset($_POST['addnew'])) {
$this->addRecord();
}
#this will check if the post value is trigger
if(isset($_POST['saveinfo'])) {
$this->updateinfo();
}
if($this->uri->segment(2) == 'add' || $this->uri->segment(2) == 'edit') {
#this display the form for products
$this->displayForm();
} else {
#this will display the job orders
$this->getAllEmployees();
}
if($this->uri->segment(2) == 'print') {
#this display the form for products
$this->pdf();
}
if($this->uri->segment(2) == 'do_upload') {
#this display the form for products
$this->do_upload();
}
#this will logout the user and redirect to the page
if($this->uri->segment(2) == 'logout') {
session_destroy();
redirect('home', 'location');
}
$data = array ( 'pageTitle' => 'Payroll System | ADMINISTRATION',
'disMsg' => $disMsg,
'mainCont' => $this->mainCont );
$this->load->view('mainTpl', $data, FALSE);
}
function do_upload(){
if($this->input->post('upload')){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('pages/employeesform', $error);
}
else{
$data=$this->upload->data();
$this->thumb($data);
$file=array(
'img_name'=>$data['raw_name'],
'thumb_name'=>$data['raw_name'].'_thumb',
'ext'=>$data['file_ext'],
'upload_date'=>time()
);
$this->Contents->add_image($file);
$data = array('upload_data' => $this->upload->data());
$this->load->view('pages/upload_success', $data);
}
}
else{
redirect(site_url('employees'));
}
}
function thumb($data){
$config['image_library'] = 'gd2';
$config['source_image'] =$data['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 275;
$config['height'] = 250;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
public function displayForm() {
$data['level'] = $this->Contents->exeGetUserLevel();
$data['status'] = $this->Contents->exeGetUserStatus();
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
if($this->uri->segment(2) == 'edit') {
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
$data['emp'] = $this->Contents->exeGetEmpToEdit($this->uri->segment(3));
$data['info'] = $this->Contents->exeGetUserInfo($this->uri->segment(3));
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
#this will add new record
public function addRecord() {
if(empty($_POST['fname']) || empty($_POST['mname']) || empty($_POST['lname']) || empty($_POST['empass']) || empty($_POST['emailadd']) || empty($_POST['gender']) || empty($_POST['datehired']) || empty($_POST['salary'])) {
$disMsg = "Please fill up the form completely.";
$_SESSION['disMsg'] = $disMsg;
} else {
$addNew = $this->Contents->exeAddNewRecord();
if($addNew['affRows'] > 0) {
$_SESSION['disMsg'] = "New Employee has been added.";
redirect('employees', 'location');
} else {
$disMsg = "Unable to add new employee.";
}
}
}
Views:
<?php echo form_open_multipart('employees/do_upload');?>
<img id="preview" style = "width: 200px; height: 200px;">
<input type="file" name = "userfile" id="input">
<br /><br />
<input type="submit" value="upload" name="upload" />
</form>
<form action="" method="post" enctype="multipart/form-data" id="empform" role="form" name="empform">
<div class="box-body">
<div class="row">
<div class="col-lg-6">
<div class="input-field col s12">
<label>Firstname</label>
<input type="text" id="fname" name="fname" class="form-control" value="<?php if(!empty($_POST['fname'])) { echo $_POST['fname']; } elseif(!empty($emp[0]['firstname'])) { echo $emp[0]['firstname']; } ?>">
</div>
<div class="input-field col s12">
<label>Middle Name</label>
<input type="text" id="mname" name="mname" class="form-control" value="<?php if(!empty($_POST['mname'])) { echo $_POST['mname']; } elseif(!empty($emp[0]['middlename'])) { echo $emp[0]['middlename']; } ?>">
</div>
<div class="input-field col s12">
<label>Password</label>
<input type="password" id="empass" name="empass" class="form-control" value="<?php if(!empty($_POST['empass'])) { echo $_POST['empass']; } ?>">
</div>
<div class="input-field col s12">
<label>Employee ID</label>
<input type="text" id="empno" name="empno" class="form-control" value="<?php if(!empty($_POST['empno'])) { echo $_POST['empno']; } elseif(!empty($emp[0]['employeeid'])) { echo $emp[0]['employeeid']; } ?>">
</div>
</div>
<div class="col-lg-4" style="padding-left:0;">
<?php if($this->uri->segment(2) == "edit") { ?>
<button type="submit" name="saveinfo" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } else { ?>
<button type="submit" name="addnew" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } ?>
</div>
</div>
</div>
</form>
As you can see in views, there are 2 forms. First form is for image upload and the other one is user registration form. How will I be able to include the image upload in the reg form and perform image upload, save user info and form validation once save button is clicked?
This is how I handle file uploads with form... it's a generic example but it should help.
View
<?php echo form_open_multipart('someController/someFunction') ?>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name">
</div>
<div class="form-group">
<label for="uploads">Upload a file</label>
<input name="uploads[]" id="fileupload" type="file" multiple="true">
</div>
<input type="submit">
<?php echo form_close() ?>
Controller
public function addRecordToTable()
{
$this->form_validation->set_rules('name' , 'Name', 'required');
if ($this->form_validation->run() == true) {
$array = array(
'name' => $this->input->post('name')
);
$record_id = $this->some_model->addData('some_table', $array);
$this->uploadFiles($record_id);
}
}
public function uploadFiles($record_id)
{
$config = array(
'upload_path' => FCPATH . "path\to\directory",
'allowed_types' => 'jpg|png|jpeg',
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
$files = $_FILES['uploads'];
foreach ($files['name'] as $key => $filename) {
$_FILES['uploads[]']['name'] = $files['name'][$key];
$_FILES['uploads[]']['type'] = $files['type'][$key];
$_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['uploads[]']['error'] = $files['error'][$key];
$_FILES['uploads[]']['size'] = $files['size'][$key];
$config['file_name'] = $filename;
$this->upload->initialize($config);
if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
if ( ! $this->upload->do_upload('uploads[]')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploads[] = $this->upload->data();
$array = array(
'record_id' => $record_id,
'filename' => $_FILES['uploads[]']['name'],
'size' => $_FILES['uploads[]']['size']
);
$this->some_model->addData('uploads', $array);
}
}
}
redirect(base_url() . 'someController/someFunction/' . $record_id);
}
Model
public function addData($table, $array)
{
$this->db->insert($table, $array);
return $this->db->insert_id();
}
Edit:
As per your comment, to insert data into multiple tables, simply modify the code in your controller so:
public function submitEmployeeDetails()
{
$this->form_validation->set_rules('value1' , 'Value 1', 'required');
$this->form_validation->set_rules('value2' , 'Value 2', 'required');
if ($this->form_validation->run() == true) {
$array1 = array(
'value1' => $this->input->post('value1')
);
$array2 = array(
'value2' => $this->input->post('value2')
);
$this->your_model->addData('employees', $array1);
$this->your_model->addData('employees_details', $array2);
}
}
So you have two arrays and you call the addData() function in the model, the first parameter specifies the name of the table and the second passes the associative array to be added.

update details ci

I am currently trying to allow a user when logged in to update their own details. So far, the user is only allowed to edit user 1 but the form does not populate either. I would like to be able to allow the specific session user to change their details, but don't know what way to go about this. Any guidance would be appreciated, thanks!
Login Controller- Login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('login_model');
}
public function index()
{
if(($this->session->userdata('user_name')!=""))
{
$this->welcome();
}
else {
$data['title']= 'MVC Application';
$this->load->view('templates/header', $data);
$this->load->view('templates/nav');
$this->load->view('login/signin', $data);
$this->load->view('templates/footer');
}
}
public function welcome()
{
$data['title']= 'MVC Application';
$this->load->view('templates/header', $data);
$this->load->view('templates/nav');
$this->load->view('login/welcome', $data);
$this->load->view('templates/footer');
}
public function login()
{
$email=$this->input->post('email');
$password=$this->input->post('pass');
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('email', 'Your Email', 'trim|required');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else{
$this->login_model->login($email,$password);
$this->welcome();
}
}
public function logout()
{
$newdata = array(
'id' =>'',
'username' =>'',
'email' => '',
'logged_in' => FALSE,
);
$this->session->unset_userdata($newdata );
session_destroy();
redirect('login/index');
}
function update()
{ $data['title']= 'MVC Application';
$this->load->view('templates/header', $data);
$this->load->view('templates/nav');
$this->load->view('login/update', $data);
$this->load->view('templates/footer');
$data = array (
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$this->load->model('login_model');
$this->login_model->update($data);
}
}
?>
Login model- Login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function login($email, $password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("mvc_user");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'id' => $rows->id,
'username' => $rows->username,
'email' => $rows->email,
'password' => $rows->password,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
function update($data)
{
$this->db->where('id', 1);
$this->db->update('mvc_user', $data);
}
}
?>
Update view (located in login folder) update.php
<div class="six columns">
<?php echo form_open('login/update'); ?>
<p>
<label for="user_name">Username</label>
<input type="text" name="user_name" id="user_name" />
</p>
<p>
<label for="user_email">Email</label>
<input type="text" name="user_email" id="user_email" />
</p>
<p>
<label for="user_password">Password</label>
<input type="text" name="user_password" id="user_password" />
</p>
<p><input type="submit" value="Save" /></p>
<?php echo form_close(); ?>
</div>
First, you need to pass the data from the Login controller to the view so that you can pre-populate the form fields:
function update() {
// Prepare data to pass to the view
$data = array (
'title' => 'MVC Application',
'username' => $this->session->userdata('username'),
'email' => $this->session->userdata('email'),
'password' => $this->session->userdata('password')
);
$this->load->view('templates/header', $data);
$this->load->view('templates/nav');
$this->load->view('login/update', $data);
$this->load->view('templates/footer');
$data = array (
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$this->load->model('login_model');
$this->login_model->update($data);
}
The view can then access the array elements as individual variables and pre-populate the input fields:
<div class="six columns">
<?php echo form_open('login/update'); ?>
<p>
<label for="username">Username</label>
<input type="text" name="username" id="username" value="<?php echo $username; ?>" />
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php echo $email; ?>" />
</p>
<p>
<label for="password">Password</label>
<input type="text" name="password" id="password" value="<?php echo $password; ?>" />
</p>
<p><input type="submit" value="Save" /></p>
<?php echo form_close(); ?>
</div>
To save the user's new data in Login_model.php, just get the id from the session:
function update($data) {
$my_id = $this->session->userdata('id');
if($my_id !== false) { // Just making sure we're logged in
$this->db->where('id', $my_id);
$this->db->update('mvc_user', $data);
}
}

Categories