Codeigniter Updating Edit Page - php

I have created an edit page which repopulates their information into the correct fields (based on the ID) and they can amend the details...
What I want now is for the Submit button to update this information in the database table?
This is the Edit Section in my Controller:
function edit($id = 0){
$this->load->model('blogmodel');
if( $this->input->post() ){ #if form submitted
$data = array();
$id = $this->input->post('id'); #to be used in the where clause for updation
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$this->blogmodel->update_blog($data,$id);
}else{
// Form Validation required
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('sEmail', 'Sender Email', 'required|valid_email');
$this->form_validation->set_message('required', '%s is required');
$this->form_validation->set_error_delimiters('<span class="error">', '</span><br />');
$sql = 'SELECT * FROM databse.blogs WHERE id = ?';
echo $sql . ' - '. $id;
$sql_params = array($id);
$query = $this->db->query($sql, $sql_params);
$form = $query->row_array();
//$date['form'] = $form;
$data['inputs'] = array('name' => $form['name'],
'address' => $form['address'],
'semail' => $form['email'],
'nickname' => $form
);
$data['Name']= $form['name'];
$data['Address']= $form['address'];
$data['Email']= $form['email'];
$this->load->view('blog_content',$data);
$data = $this->input->post();
$result = $this->blogmodel->update_blog($data,$id);
$this->load->view('blog_success');
}
}
}
So Far this is my Model:
function send_blog(&$data){
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$sql = "UPDATE database.blogs (name, address, email) WHERE id = $id
VALUES (".$this->db->escape($data['name']).",
".$this->db->escape($data['address']).",
'".$data['sEmail']."');";
$this->db->query($sql);
}
function update(&$data,$id){
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$this->db->where('id', $this->input->post('id'));
$this->db->update('blog', $data);
}
}

What is the current_url() here? I'm guessing it to be function edit(). In your function edit just do the below changes:
function edit($id = 0){
if( $this->input->post() ){ #if form submitted
$data = array();
$id = $this->input->post('id'); #to be used in the where clause for updation
/*
Retrieve all the post variables in the $data and send to model for updation
*/
$this->your_model->update_function( $data, $id );
redirect('controller/edit/'.$id, 'refresh'); #redirect to the same function to show the form or success page
}else{
/*
Your rest of the function as it is
*/
}
}
Update
Your controller changes:
function edit($id = 0){
if( $this->input->post() ){ #if form submitted
$data = array();
$id = $this->input->post('id'); #to be used in the where clause for updation
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$data['nickname'] = $this->input->post('nickname');
$data['blogregion'] = $this->input->post('blogregion');
$data['startdate'] = $this->input->post('startdate');
$data['blogtitle'] = $this->input->post('blogtitle');
$data['timesperweek'] = $this->input->post('timesperweek');
$data['profiletext'] = $this->input->post('profiletext');
$data['abouttext'] = $this->input->post('abouttext');
$data['status'] = 0;
$data['userid'] = $id;
$this->newblogsetupmodel->update_blogforus( $data, $id );
redirect('newblogsetup/edit/'.$id, 'refresh'); #redirect to the same function to show the form or success page
}else{
#rest of the controller here
}
}
Your model changes:
function update_blogforus($data, $id){
echo "<pre>";print_r( $data );die; #to print the data received from controller, see if its coming okay or make correction in the controller for the same
/*$data['name'] = $data['name'];
$data['address'] = $data['address'];
$data['sEmail'] = $data['sEmail'];
$data['nickname'] = $data['nickname'];
$data['blogregion'] = $data['blogregion'];
$data['startdate'] = $data['startdate'];
$data['blogtitle'] = $data['blogtitle'];
$data['timesperweek'] = $data['timesperweek'];
$data['profiletext'] = $data['profiletext'];
$data['abouttext'] = $data['abouttext'];
$data['status'] = 0;
//$data['userid'] = $data['user']->id;
*/
$this->db->where('id', $id);
$this->db->update('newblogsetup', $data);
echo $this->db->last_qeury();die; #to see the query being executed, run it in your phpMyadmin and see if its updating as required.
}
New Changes
Controller:
$data['id'] = $id; #save the data in an element to echo in the hidden field of the form
$this->load->view('newblogsetup_sent', $data); #load the data to the page
In your edit page change this line
<?php echo form_hidden('id');?>
To:
<?php echo form_hidden( 'id', $id );?>

Related

Check duplication while uploading to database

I need to find duplicated details in the existing table while uploading a Excel file that contains some details,i need to find that by phone number and customer name. I am using mattexcel to upload the data into database.
I don't want to insert that details if it is in there but other details must insert into that table
Controller
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
$data['customername'] = $row['customername'];
$data['chassis'] = $row['chassis'];
$data['model'] = $row['model'];
$data['branchcode'] = $row['branchcode'];
$data['delivery'] = $row['delivery'];
$data['customerid'] = $row['customerid'];
$data['phone'] = $row['phone'];
$data['invoicedate'] = $row['invoicedate'];
$data['dse'] = $row['dse'];
$data['branch'] = $row['branch'];
$data['finance'] = $row['finance'];
$data['dono'] = $row['dono'];
$data['invoice'] = $row['invoice'];
$data['zsm'] = $row['zsm'];
$data['sm'] = $row['sm'];
$data['agm'] = $row['agm'];
$data['dsecode'] = $row['dsecode'];
$data['address'] = $row['address'];
$data['email'] = $row['email'];
$data['color'] = $row['color'];
$data['extendedwarrenty'] = $row['extendedwarrenty'];
$data['autocaddownload'] = $row['autocaddownload'];
$data['numberplate'] = $row['numberplate'];
$data['mcpstatus'] = $row['mcpstatus'];
$data['plandt'] = $row['plandt'];
$data['planok'] = $row['planok'];
$data['fasttag'] = $row['fasttag'];
// $data['settilment_pdf_path'] = $row['settilment_pdf_path'];
$data['rcstatus'] = $row['rcstatus'];
$branch = Branch::where([['branch_code', $row['branchcode']], ['status', 0]])->first();
$registration_id = Registration::orderBy('registration_id', 'desc')->take(1)->get();
if (count($registration_id) > 0) {
$regid = $registration_id[0]->registration_id;
$regid = $regid + 1;
} else {
$regid = 1;
}
$register = new Registration();
$register->registration_id = $regid;
$register->customername = $row['customername'];
$register->chassis = $row['chassis'];
$register->model = $row['model'];
$register->branchcode = $row['branchcode'];
$register->delivery = $row['delivery'];
$register->customerid = $row['customerid'];
$register->phone = $row['phone'];
$register->invoicedate = $row['invoicedate'];
$register->dse = $row['dse'];
$register->branch = $row['branch'];
$register->finance = $row['finance'];
$register->dono = $row['dono'];
$register->invoice = $row['invoice'];
$register->zsm = $row['zsm'];
$register->sm = $row['sm'];
$register->agm = $row['agm'];
$register->dsecode = $row['dsecode'];
$register->address = $row['address'];
$register->email = $row['email'];
$register->color = $row['color'];
$register->extendedwarrenty = $row['extendedwarrenty'];
$register->autocaddownload = $row['autocaddownload'];
$register->numberplate = $row['numberplate'];
$register->mcpstatus = $row['mcpstatus'];
$register->plandt = $row['plandt'];
$register->planok = $row['planok'];
$register->fasttag = $row['fasttag'];
$register->rcstatus = $row['rcstatus'];
$register->dealership = $branch->dealership_id;
$register->zone = $branch->zone_id;
$register->dh = $branch->dh_id;
$register->status = '0';
$register->created_user_id = Session::get('created_id');
$register->save();
$regidn = Registration::orderBy('registration_id', 'desc')->get();
$regidd = $regidn[0]->registration_id;
$ssitrack = new Ssi_track();
$ssitrack->registration_id = $regid;
$ssitrack->ssi_track_id = $regid;
$ssitrack->save();
$ssitrackk = Ssi_track::orderBy('ssi_track_id', 'desc')->get();
$ssitrackk = $ssitrackk[0]->registration_id;
}
});
}
return back()->with('success', 'Your File Is Successfully Uploaded To Database!');
}
Option 1. You can add unique values combination in migration.
Schema::table('your_table_name', function (Blueprint $table) {
$table->unique(['phone ','customername ']);
});
This won't let you insert same combination values for these column combination, however it also throws error stopping you import function.
Option 2 (Better).
Check if value already exits and ignore import for that column.
$old_customer = Regiter::where('phone', $row['phone'])->where('customername', $customername )->first();
//Inser only if customer not found
if(is_null($old_customer))
{
//INSERT QUERY
}
To decrease number of query you can pluck name and phone with single query or use any other optimization tricks.

how to input the parent id into database in different table

I have table -> subkategori
and I can't insert the id_kategori attribute to table portfolio
i have a code for the model :
function get_subcategories($id_kategori){
$query = $this->db->query("SELECT id_kategori from subkategori WHERE id_subkategori=".$this->input->post('a'));
return $query->result();
}
and the controller here :
if ($this->input->post('a')!=''){
$this->load->model('Model_app');
$this->model_app->get_subcatoegories('$id_kategori');
}else{
$id_kategori = '';
}
$data = array(
'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
'id_kategori'=>$id_kategori
);
$this->input->post('a') as you mentioned here I assume that you have input in the form and its name is a.
In Controller
if (!empty($this->input->post('a')))
{
$this->load->model('Model_app');
$id = $this->model_app->get_subcatoegories($this->input->post('a'));
if (empty($id)) {
$id_kategori = '';
} else {
$id_kategori = $id[0]['id_kategori'];
}
}else{
$id_kategori = '';
}
$data = array(
'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
'id_kategori'=>$id_kategori
);
In Model
function get_subcategories($id_kategori)
{
$query = $this->db->query("SELECT id_kategori FROM subkategori WHERE id_subkategori = $id_kategori");
return $query->result_array();
}
You can get last insterted if with $this->db->insert_id();
In your, if statement you didn't assign the database value to the $id_kategori variable. Hence while inserting the empty value into the table it inserts as 0(int field).
And also when you pass a variable to a function it should not be single quoted. You have to pass the post variable but you are passing a variable which is undefined.
if ($this->input->post('a')!=''){
$this->load->model('Model_app');
$category = $this->model_app->get_subcatoegories($this->input->post('a'));
$id_kategori = $category['id_kategori];
}else{
$id_kategori = '';
}
$data = array(
'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
'id_kategori'=>$id_kategori
);

Undefined variable in array

I have been getting this error Undefined variable nik when I want to access the array from for each this array getting information from the database
View
foreach ($data as $user) {
$id_user = $user->id_user;
$nama = $user->nama;
$nik = $user->nik;
echo $nik;
$alamat = $user->alamat;
$no_telp = $user->no_telp;
$pass = md5($user->password);
$name = $user->name;
}
Controller
public function user_akun_detail() {
$id_user = $this->input->get('id');
$detail['data'] = $this->Madmin->user_akun_detail($id_user);
$this->load->view('admin/Detail_user_pemilih', $detail);
$this->session->set_flashdata('id_user', $id_user);
}
Model
public function user_akun_detail($id_user) {
$this->db->select('*');
$this->db->from('akun');
$this->db->join('detail_user', 'detail_user.id_user = akun.id_user');
$this->db->join('image_user', 'akun.id_user = image_user.id_user');
$this->db->where('akun.id_user', $id_user);
$query = $this->db->get();
return $query->result();
}

Session Doesn't work in codeigniter

In my project, session is work fine before few days.But now it doesn't work. i can't find the error. plsease help me. it displays error called Severity: Notice
Message: Undefined index: firstname
Filename: user_include/header.php
Line Number: 5
A PHP Error was encountered
Severity: Notice
Message: Undefined
index: id
Filename: user_include/header.php
Line Number: 7
controller
/ Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
//$this->load->view('admin_page');
$this->home();
}else{
$this->load->view('user_site/login_form');
}
} else {
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('user_site/login_form', $data);
}
}
}
// Logout
public function logout() {
// Removing session data
$sess_array = array(
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('user_site/login_form', $data);
}
}
?>
model
// Read data using username and password
public function login($data) {
$condition = "email =" . "'" . $data['email'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
view
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}
the error is in you user_include/header.php , check the id and firstname are set before you echo them out.
In your model replace following code by given code:
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
To
public function read_user_information($email) {
$this->db->select('firstname, email, id');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
In your controller replace following code by given
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
To
$email = $this->input->post('email');
$user_details = $this->login_database->read_user_information($email);
if ($user_details != false) {
// Add user data in session
$this->session->set_userdata('logged_in', $user_details);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
In view, replace your code by following:
<?php
$user_details = $this->session->userdata['logged_in']);
if ($user_details != "") {
$firstname = $user_details['firstname'];
$email = $user_details['email'];
$id = $user_details['id'];
} else {
header("location: login");
}

how to get primary key value of newly inserted user in zend

i have a problem on my project im currently working on and
this is my register controller
every time a user registers there will be a default image that will be displayed in their profile
public function registerAction()
{
$form = new Application_Form_Users();
$form->submit->setLabel('Register');
$this->view->form = $form ;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$id = $form->getValue('uid');
$firstname = $form->getValue('firstname');
$lastname = $form->getValue('lastname');
$email = $form->getValue('email');
$username = $form->getValue('username');
$password = $form->getValue('password');
$vpassword = $form->getValue('vpassword');
if ($password == $vpassword) {
$register = new Application_Model_DbTable_Users();
$password = md5($password);
$register->addUser($firstname , $lastname , $email , $username , $password );
if ($register) {
$register = new Application_Model_DbTable_Users();
$uid = $form->populate($register->getUser($id));
$addimg = new Application_Model_DbTable_Images();
$imagepath = APPLICATION_PATH.'/../public/upload/';
$addimg->addImage($uid , $imagepath);
}
$this->_helper->redirector('index');
} else {
$this->view->errorMessage = "Passwords don't match.";
}
} else {
$form->populate($formData);
}
}
}
this is my function to add default image path into my database
public function addImage($uid , $imgpath)
{
$data = array(
'uid' => $uid ,
'imgpath' => $imgpath ,
);
$this->insert($data);
}
but i got an error because my uid is null my question is how to get the value of uid in my users table, also users table and images table have a relation.
If you are using Zend_Db_Table then you can do something like this in addUser():
public function addUser($firstname , $lastname , $email , $username , $password ){
$user = $this->createRow();
$user->fname = $firstname;
$user->lname = $lastname;
...
$user->save();
return $user->id;
}
This will return you user id so you can do:
$id = $register->addUser($firstname , $lastname , $email , $username , $password );
and
$addimg->addImage($id , $imagepath); //$id, not $uid !
You can put a default value for $imgpath in your database for each new entry.
You can use the lastInsertId() function within the Zend_Db_Adapter class.
http://framework.zend.com/manual/1.12/en/zend.db.adapter.html#zend.db.adapter.write.lastinsertid
In your case it should be:
$this->getAdapter()->lastInsertId()
after your last line in the addImage method.
Warning: This does not work with all SQL adapters (like PostgreSQL)
From what i can get from your code, you're adding a new user, and then, adding an image related to his id.
$uid = $form->populate($register->getUser($id));
$addimg = new Application_Model_DbTable_Images();
$imagepath = APPLICATION_PATH.'/../public/upload/';
$addimg->addImage($uid , $imagepath);
And, you get an "error" because $uid is null. But $id shouldn't be null, and it should be the ID of the user you just added.
So you might try this and see if it works for you
$addimg->addImage($id , $imagepath);

Categories