Get last insert_id in the URL in codeigniter - codeigniter

i have one requirement from in my application..so when ever user insert details in the requirement.and then submit..the mail will go to the particular vendor with one link..when vendor click on the link i redirect the page to login page..
So what i want to do is i want to send email link with last inserted id..
Here is my controller:
public function requirement()
{
$data["msg"]="";
$this->load->model('RequirementModel');
$data['user']=$this->RequirementModel->getusers();
$data['rolename']=$this->RequirementModel->getrolename();
if($this->input->post())
{
$this->RequirementModel->add_requirement($this->input->post());
$all_users = $this->input->post('user_id');
foreach($all_users as $key)
{
$get_email = $this->RequirementModel->get_user_email_by_id($key);
$req_id = $this->input->post('req_id');
$role_name = $this->input->post('role_name');
$vacancies = $this->input->post('vacancies');
$experience = $this->input->post('experience');
$jd = $this->input->post('jd');
$hiring_contact_name = $this->input->post('hiring_contact_name');
$hiring_contact_number = $this->input->post('hiring_contact_number');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://md-in-42.webhostbox.net',
'smtp_port' => 465,
'smtp_user' => 'test3#clozloop.com',
'smtp_pass' => 'test3'
);
$this->load->library('email',$config);
$this->email->set_mailtype("html");
$this->email->from('test3#clozloop.com', 'bharathi');
$this->email->to($get_email);
$this->email->subject('this is our requirements pls go through it');
$link = 'Click on this link - <a href="http://localhost/job_portal/index.php/Login/signin>Click Here</a>';
$this->email->message($link);
print_r($get_email);
if($this->email->send())
{
echo "email sent";
}
else
{
echo "email failed";
}
}
}
$this->load->view('Requirements/requirements',$data);
}
Can anyone help me..
Thanks in advance..

What you need is the database helper function insert_id(), it returns the id of the last insert: https://www.codeigniter.com/userguide3/database/helpers.html?highlight=insert_id
Have your add_requirement function of the RequirementModel model return the insert_id like so:
return $this->db->insert_id();
Then just save that value when you call the function:
$insert_id = $this->RequirementModel->add_requirement($this->input->post());

Related

Method not allowed exception while updating a record

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpExceptionNomessage
I'm getting this error while trying to update a record in the database. Don't know what's the problem. This question might be a duplicate but I've checked all and couldn't find the answer. Please Help me with this.
Controller Update Method:
public function updateEvent(Request $request, $id=''){
$name = $request->name;
$startdate = date_create($request->start_date);
$start_date = $startdate;
$time = $request->start_time;
$start_time = $time;//date("G:i", strtotime($time));
$endDate = date_create($request->end_date);
$end_date =$endDate;
$time_e = $request->end_time;
$end_time = $time_e;//date("G:i", strtotime($time_e));
$location = $request->location;
$description = $request->description;
$calendar_type = $request->calendar_type;
$timezone = $request->timezone;
if ($request->has('isFullDay')) {
$isFullDay = 1;
}else{
$isFullDay = 0;
}
DB::table('events')->where('id', $id)->update(
array(
'name' => $name,
'start_date' => $start_date,
'end_date' => $end_date,
'start_time' => $start_time,
'end_time' => $end_time,
'isFullDay' =>$isFullDay,
'description' => $description,
'calendar_type' => $calendar_type,
'timezone' => $timezone,
'location' => $location,
));
// Event Created and saved to the database
//now we will fetch this events id and store its reminder(if set) to the event_reminder table.
if(!empty($id))
{
if (!empty($request->reminder_type && $request->reminder_number && $request->reminder_duration)) {
DB::table('event_reminders')->where('id', $id)->update([
'event_id' => $id,
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
}
else{
DB::table('event_reminders')->insert([
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
return redirect()->back();
}
Route:
Route::post('/event/update/{id}', 'EventTasksController#updateEvent');
Form attributes :
<form action="/event/update/{{$event->id}}" method="POST">
{{ method_field('PATCH')}}
i'm calling the same update function inside my calendar page and it working fine there. Don't know why it doesn't work here.
Check the routeing method.
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
patch should be the method called on route facade.
Change your route to patch:
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
For your comment:
You can send the method to the ajax call by something like data-method attribute on the element you click on,take the method and use it in your ajax call. see this question/answer for help. How to get the data-id attribute?

Codeigniter 3: send account activation email fails

I am working on a Register and Login application with CodeIgniter 3 and Twitter Bootstrap.
When a user registers, an email should be send to the address he/she provided, with an account confirmation link. The problem is that the confirmation email does not send.
In the Usermodel I have:
public function activationEmail($first_name='', $last_name='', $email='', $verification_key='')
{
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.code-love.tk',
'smtp_port' => 465,
'smtp_user' => 'razvan#code-love.tk',
'smtp_pass' => '******',
'smtp_crypto' => 'ssl',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$messg = 'Wellcome, '. $first_name . ' ' . $last_name . '! Click the <strong>confirmation link</strong> to confirm your account.';
$this->email->initialize($config);
$this->email->set_newline('\r\n');
$this->email->from('mail.code-love.tk','Razvan Zamfir');
$this->email->to($email);
$this->email->subject('Account activation');
$this->email->message($messg);
if (!$this->email->send()) {
show_error($this->email->print_debugger());
}
else {
echo 'Your e-mail has been sent!';
}
}
In my Signup controller I have this code:
public function signup() {
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
if ($this->form_validation->run()) {
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$password = $this->input->post('password');
$verification_key = md5($email);
$date_created = date('Y-m-d H:i:s');
$date_updated = date('Y-m-d H:i:s');
$active = 0;
// Load user model
$this->load->model('Usermodel');
// If email does not already exist in the database
// signup new user
if (!$this->Usermodel->email_exists($email)) {
if ($this->Usermodel->user_register($first_name, $last_name, $email, $password, $verification_key, $date_created, $date_updated, $active) && $this->Usermodel->activationEmail($first_name, $last_name, $email, $verification_key)) {
$this->session->set_flashdata("signup_success", "Your account has just bean created. You must confirm it before you can sign in. We have send you a confirmation email at $email for this purpose.");
} else {
// unless sigup does not fail for whatever reason
$this->session->set_flashdata("signup_failure", "We ware unable to create your account.");
}
redirect('signup');
} else {
// If email is already in the database
// urge user to sign in (redirect to signup page too)
$this->session->set_flashdata("email_exists", "The email address $email already exists in the database. Please signin.");
redirect('signin');
}
} else {
$this->load->view('signup');
}
}
The sign up does happen, with the error below, and the verification email is not send. I am not doing this from a local XAMPP/WAMP/MAMP server, but from a "live" one, you can signup yourself.
Severity: Warning
Message: fsockopen(): php_network_getaddresses: getaddrinfo failed: Name or service not known
Filename: libraries/Email.php
Line Number: 1950
Backtrace:
File: /home/roxoqdat/code-love.tk/ciauth/application/models/Usermodel.php
Line: 52
Function: send
File: /home/roxoqdat/code-love.tk/ciauth/application/controllers/Signup.php
Line: 42
Function: activationEmail
File: /home/roxoqdat/code-love.tk/ciauth/index.php
Line: 292
Function: require_once
What am I doing wrong?
Check if you have the required SMTP service.
Try with google SMTP service.
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx',
'smtp_pass' => 'xxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('mygmail#gmail.com', 'myname');
$this->email->to('target#gmail.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$result = $this->email->send();
Next try with:
$config = array('mailtype' => 'html');
Remove the rest from $config = array.
First of all, after setting flashdata, I don't see you redirecting the user to where they can see it...
Also, send the mail first, then you set flash data as An Activation Link Has Been Sent To Your Email, Please Check Your Email To Activate Your Account!
So,
User Registers,
An email is sent to them only if it doesn't exist already,
Set flashdata for any errors that may arise... Eg:
Assign a variable to the email sending function:
$send_email = $this->activationEmail('params');
In your activationEmail function, make sure there is a simple control structure like this:
$success=$this->email->send();
if($success){ return true; } else{ return false; }
Now in your controller, compare to see if mail is actually sent:
if($send_email == true){ $this->session->flashdata('success','Your success message');
// use the redirect() helper function to the function that loads your view
} else { //set failed flashdata and redirect to where you want it seen like above}
You then will know where the problem is.
Let the program flow in your mind first, then implement it. Try that first and get back to me right after.
Hope it somehow helps
Debug whether your parameters are passing or not (specially last_name). Try to write the model method like this to avoid showing errors
public function activationEmail($first_name='', $last_name='', $email='', $verification_key='')
Try adding header to your email (You are setting mailtype twice, might be an issue).
$this->email->set_header('MIME-Version', '1.0; charset=utf-8');
$this->email->set_header('Content-type', 'text/html');

how can i get the current_link id?

I am using laravel 5.2.I want to get the id of current_link.Please help me to find the id of current_link.
public function checkUrl(){
$current_link = $_SERVER['REQUEST_URI'];
$current_link=ltrim($current_link, '/');
$current_link=ltrim($current_link, 'cable');
$current_link=ltrim($current_link, '/');
$plink = DB::table('roles')->where('id',$current_link->id)->get();
// print_r($plink);
// die();
$dlink= DB::table('my_roles')->where('role_id',$current_link->role_id)->get();
if($plink!=$dlink){
Session::flash('flash_notification', array('level' => 'success', 'message' => 'Error!! You dont have the permission to access this page'));
return Redirect::action('Admin\DashboardController#index');
}
}

Codeigniter captcha

I ran into a small problem what i cant figure out.
I would liked to use the captcha helper without database but nothing seems to be working.
in the construct i created a variable which generates a random string
public function __construct()
{
parent::__construct();
$this->rand = random_string('numeric', 4);
}
passed this variable to the captcha values like this:
$vals = array(
'word' => $this->rand,
'img_path' => './captcha/',
'img_url' => base_url() . 'captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
and wanted to validate it with a callback function like this
function captcha_check()
{
if($this->input->post('code') != $this->rand)
{
$this->form_validation->set_message('captcha_check', 'Wrong captcha code, hmm are you the Terminator?');
return false;
}
}
And nothing works, the problem is, captcha code is show with the image, the problem is the validation, if i type in the correct numbers in my captcha field it always showing me the error, no mather what i type in, could please someone give me a hint?
html:
<label for="code">Count please </label>
<?php echo $rand; ?>
<input type="text" id="code" name="code" class="span3" />
validation line:
$this->form_validation->set_rules('code', 'Captcha', 'required|callback_captcha_check');
Modify your callback function like this:
function captcha_check()
{
if($this->input->post('code') != $this->rand)
{
$this->form_validation->set_message('captcha_check', 'Wrong captcha code, hmm are you the Terminator?');
return false;
}
return true;
}
EDIT:
You need to move this line $this->rand = random_string('numeric', 4); out of the constructor because on each load of the controller it generates a new string, resulting in different values on the captcha initial load and the captcha verification. Simply place it before the $vals initialization.
* Example of captcha validation without database
* Instead of it used session to store captcha value
* The images will be deleted after the use
--
public function index()
{
$this->load->helper(array('form', 'url','captcha'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
$this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha');
if($this->form_validation->run() == FALSE)
{
$original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
$original_string = implode("", $original_string);
$captcha = substr(str_shuffle($original_string), 0, 6);
//Field validation failed. User redirected to login page
$vals = array(
'word' => $captcha,
'img_path' => './captcha/',
'img_url' => 'http://mycodeignitor.org/captcha/',
'font_path' => BASEPATH.'fonts/texb.ttf',
'img_width' => 150,
'img_height' => 50,
'expiration' => 7200
);
$cap = create_captcha($vals);
$data['image'] = $cap['image'];
if(file_exists(BASEPATH."../captcha/".$this->session->userdata['image']))
unlink(BASEPATH."../captcha/".$this->session->userdata['image']);
$this->session->set_userdata(array('captcha'=>$captcha, 'image' => $cap['time'].'.jpg'));
$this->load->view('index_index',$data);
}
else
{
if(file_exists(BASEPATH."../captcha/".$this->session->userdata['image']))
unlink(BASEPATH."../captcha/".$this->session->userdata['image']);
$this->session->unset_userdata('captcha');
$this->session->unset_userdata('image');
redirect('home', 'refresh');
}
}
public function validate_captcha(){
if($this->input->post('captcha') != $this->session->userdata['captcha'])
{
$this->form_validation->set_message('validate_captcha', 'Wrong captcha code, hmm are you the Terminator?');
return false;
}else{
return true;
}
}
$vals = array(
'word' => $this->rand,
'img_path' => './captcha/',
'img_url' => base_url() . 'captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
$this->session->set_userdata($cap);
function captcha_check()
{
if($this->input->post('code') == $this->session->userdata('word'))
{
return true;
}else{
$this->form_validation->set_message('captcha_check', 'Wrong captcha code, hmm are you the Terminator?');
return false;
}
}
Try using captcha service like MTCaptcha, where database is not require to setup. Captcha can be directly validated in back-end (here in this case codeigniter).

CodeIgniter: Passing fields to user_profiles database with Tank_auth

I'm wracking my brain on what is probably a simple issue. Relatively new to MVC and codeigniter. I'm using tank_auth for user registration, and it comes with a db table user_profiles which I've altered slightly to add things like 'firstname', 'lastname', 'homephone', etc.
I've added the appropriate fields to my register_form.php view and following advice from this question: Tank Auth Adding Fields and others, tried to update all necessary stuff. Unfortunately, while the users table gets populated properly, the user_profiles table does not. I've double checked with firebug that the view is posting properly, but the model is not picking up the data, and I keep getting the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: firstname
Filename: tank_auth/users.php
Line Number: 382
Using var_dump, I can see that the controller function is not receiving 'firstname' or anything else and they are NULL, but the data going into users is being sent properly.
Here's the relevant code:
Model:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Controller:
function register()
{
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
$this->_show_message($this->lang->line('auth_message_registration_disabled'));
} else {
$use_username = $this->config->item('use_username', 'tank_auth');
if ($use_username) {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
}
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('firstname', 'Firstname', 'trim|xss_clean');
$this->form_validation->set_rules('lastname', 'Lastname', 'trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
$captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
$use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
if ($captcha_registration) {
if ($use_recaptcha) {
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
} else {
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
}
$data['errors'] = array();
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('homephone'),
$this->form_validation->set_value('cellphone'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
if ($captcha_registration) {
if ($use_recaptcha) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$data['use_username'] = $use_username;
$data['captcha_registration'] = $captcha_registration;
$data['use_recaptcha'] = $use_recaptcha;
$this->load->view('auth/register_form', $data);
}
}
View:
$firstname = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => set_value('firstname'),
'maxlength' => 40,
'size' => 30,
);
...
<tr>
<td><?php echo form_label('First Name', $firstname['id']); ?></td>
<td><?php echo form_input($firstname); ?></td>
<td style="color: red;"><?php echo form_error($firstname['name']); ?><?php echo isset($errors[$firstname['name']])?$errors[$firstname['name']]:''; ?></td>
</tr>
I have been working on this far too long, am hoping that a fresh (and knowledgeable) pair of eyes can see what I cannot.
The data to be recorded in user_profile is passed along the folllowing chain:
view -> controller -> library/tank_auth/create_user() -> model/users/users/create_user() -> model/create_profile
Therefore you need to make sure that the variable is passed along every time.
Here is my working solution, building up on the modifications that you mentioned in the question:
VIEW + CONTROLER:
Your solution is good
LIBRARY
function create_user($username, $email, $password, $firstname, $lastname, $company='', $email_activation)
{
if ((strlen($username) > 0) AND !$this->ci->users->is_username_available($username)) {
$this->error = array('username' => 'auth_username_in_use');
} elseif (!$this->ci->users->is_email_available($email)) {
$this->error = array('email' => 'auth_email_in_use');
} else {
// Hash password using phpass
$hasher = new PasswordHash(
$this->ci->config->item('phpass_hash_strength', 'tank_auth'),
$this->ci->config->item('phpass_hash_portable', 'tank_auth'));
$hashed_password = $hasher->HashPassword($password);
$data = array(
'username' => $username,
'password' => $hashed_password,
'email' => $email,
'last_ip' => $this->ci->input->ip_address(),
);
$data_profile = array(
'firstname' => $firstname,
'lastname' => $lastname,
'company' => $company,
);
if ($email_activation) {
$data['new_email_key'] = md5(rand().microtime());
}
if (!is_null($res = $this->ci->users->create_user($data, $data_profile, !$email_activation))) {
$data['user_id'] = $res['user_id'];
$data['password'] = $password;
unset($data['last_ip']);
return $data;
}
}
return NULL;
}
MODEL:
function create_user($data, $data_profile, $activated = TRUE)
{
$data['created'] = date('Y-m-d H:i:s');
$data['activated'] = $activated ? 1 : 0;
var_dump($data);
if ($this->AuthDb->insert($this->table_name, $data)) {
$user_id = $this->AuthDb->insert_id();
$this->create_profile($user_id, $data_profile);
return array('user_id' => $user_id);
}
return NULL;
}
[...]
private function create_profile($user_id, $data_profile)
{
$this->AuthDb->set('user_id', $user_id);
$this->AuthDb->set('firstname', $data_profile['firstname']);
$this->AuthDb->set('lastname', $data_profile['lastname']);
$this->AuthDb->set('company', $data_profile['company']);
return $this->AuthDb->insert($this->profile_table_name);
}
You need to pass $firstname as a parameter to the function...
private function create_profile($user_id, $firstname)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Ok so I figured it out, in case anyone googles this answer down the line. I'm not sure if this is the 'proper' or most elegant solution, but does fine for my purposes. I edited the create_profile function like so:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$data = array(
'firstname' => $this->input->post('firstname'),
);
$this->db->insert($this->profile_table_name, $data);
}

Resources