I have a web application that need to send message to many friends.But i suffer an error..please help me....
Here below is the my controller
public function message(){
$this->form_validation->set_rules('message','Message', 'required');
$this->form_validation->set_rules('friend_id[]','Recipients', 'required');
if($this->form_validation->run()){
$data = $this->input->post("friend_id[]");
unset($data['submit']);
$this->load->model('Queries');
$message=$this->Queries->saveMessage();
if($message){
echo "Success";
}else{
echo "error";
}
}
else{
echo validation_errors();
}
}
This is My Model
public function saveMessage($data){
$i=0;
foreach($data['friend_id'] as $friend_id){
$record = array(
'friend_id' => $friend_id,
'message' => $data['message']
);
$this->db->insert('tbl_messages', $record);
$i++;
}
return $data;
}
When i run it..it display error and no data is inserted in database
Hope this will help you :
Your controller method message() should be like this :
public function message()
{
$this->form_validation->set_rules('message','Message', 'required');
$this->form_validation->set_rules('friend_id[]','Recipients', 'required');
if($this->form_validation->run())
{
$friend_ids = $this->input->post("friend_id[]");
$message = $this->input->post("message");
unset($data['submit']);
$this->load->model('Queries');
$insert = $this->Queries->saveMessage($friend_ids, $message);
if($insert)
{
echo "Success";
}
else
{
echo "error";
}
}
else
{
echo validation_errors();
}
}
Your model method saveMassage() should be like this :
public function saveMessage($friend_ids , $message)
{
foreach($friend_ids as $friend_id)
{
$record = array('friend_id' => $friend_id,'message' => $message);
$this->db->insert('tbl_messages', $record);
}
return true;
}
Related
Here is my function
function store(){
$this->load->library('form_validation');
$this->form_validation->set_rules('shorthand','Shorthand','required|is_unique[locations.shorthand]');
if($this->form_validation->run() == FALSE){
redirect('locations');
} else {
$id = $this->input->post('location_id');
$location_name = ucwords(strtolower($this->input->post('location_name')));
$shorthand = strtolower($this->input->post('shorthand'));
$station = ucwords(strtolower($this->input->post('station')));
$data = array(
'location_name'=>$location_name,
'shorthand'=>$shorthand,
'station'=>$station
);
}if($id){
$result = $this->location_model->update($data,$id);
if($result > 0){
$this->session->set_flashdata('success', 'Update successfull!');
}else{
$this->session->set_flashdata('error', 'Failed to update!');
}
redirect('locations');
}else{
$result = $this->location_model->create($data);
if($result > 0){
$this->session->set_flashdata('success', 'Location added!');
}else{
$this->session->set_flashdata('error', 'Failed to add location!');
}
redirect('locations');
}
}
The shorthand updates fine but station and location_name wont update no matter what I do. But if I remove this chunk of code.
$this->load->library('form_validation');
$this->form_validation->set_rules('shorthand','Shorthand','required|is_unique[locations.shorthand]');
if($this->form_validation->run() == FALSE){
redirect('locations');
} else {
All of the fields will update. Can you please look at my codes? Thanks in advance.
Here is my Update Query
function update($data, $id){
$this->db->where('location_id', $id);
$this->db->update('locations', $data);
return $this->db->affected_rows();
}
I think this what you need. Please manage according to your need
$locations = $this->db->get_where('locations', array('location_id' => $id))->row();
$original_value = $locations->shorthand;
if($this->input->post('shorthand') != $original_value) {
$is_unique = '|is_unique[locations.shorthand]';
} else {
$is_unique = '';
}
$this->form_validation->set_rules('shorthand','Shorthand','required|trim|xss_clean'.$is_unique);
Guys for the people who have commented, thank you but I have already solved the problem it
was inside controller I forgot to put else after this line
if($this->form_validation->run() == FALSE){
redirect('locations');
}
This is how the whole function looks now
function store(){
$this->form_validation->set_rules('location_name','Location_name','required');
$this->form_validation->set_rules('shorthand','Shorthand','required|callback_locationExists');
$this->form_validation->set_rules('station','Station','required');
$id = $this->input->post('location_id');
$location_name = ucwords(strtolower($this->input->post('location_name')));
$shorthand = strtolower($this->input->post('shorthand'));
$station = ucwords(strtolower($this->input->post('station')));
$data = array(
'location_name'=>$location_name,
'shorthand'=>$shorthand,
'station'=>$station,
);
if($this->form_validation->run() == FALSE){
redirect('locations');
}else{
if($id){
$result = $this->location_model->update($data,$id);
if($result > 0){
$this->session->set_flashdata('success', 'Update successfull!');
}else{
$this->session->set_flashdata('error', 'Failed to update!');
}
redirect('locations');
}else{
$result = $this->location_model->create($data);
if($result > 0){
$this->session->set_flashdata('success', 'Location added!');
}else{
$this->session->set_flashdata('error', 'Failed to add location!');
}
redirect('locations');
}
}
}
Thanks for reading
I am trying to get users details from the database and put it in session so that it can be used in the view. I have tried all I can but I keep getting error. Undefined Variable Email.
MODEL:
function login($username, $password)
{
$this->db->select('authTbl.id, authTbl.password, authTbl.username, authTbl.email, authTbl.mobile');
$this->db->from('users as authTbl');
$this->db->where('authTbl.username', $username);
$this->db->where('authTbl.isDeleted', 0);
$query = $this->db->get();
$user = $query->result();
if(!empty($user)){
if(verifyHashedPassword($password, $user[0]->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}
CONTROLLER:
function isLoggedIn()
{
$isLoggedIn = $this->session->userdata('isLoggedIn');
$data['title'] = 'Login';
if(!isset($isLoggedIn) || $isLoggedIn != TRUE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
redirect('posts');
}
}
/**
* This function used to logged in user
*/
public function login()
{
$this->load->library('form_validation');
$data['title'] = 'Login';
$this->form_validation->set_rules('username', 'Username', 'required|max_length[128]|trim');
//$this->form_validation->set_rules('password', 'Password', 'required|max_length[32]|');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->user_model->login($username, $password);
if(count($result) > 0)
{
foreach ($result as $res)
{
$sessionArray = array('id'=>$res->id,
'username'=>$res->username,
'email'=>$res->email,
'mobile'=>$res->mobile,
'isLoggedIn' => TRUE
);
$this->session->set_userdata($sessionArray);
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
}
}
else
{
$this->session->set_flashdata('login_fail', 'Email or password mismatch');
redirect('users/login');
}
}
}
VIEW:
<?php echo $email; ?>
You are creating the session for user information
Try to fetch the session data :
echo $this->session->userdata('email');
or trying to pass the data in views $data
$email will not work because writing $email means ordinary variable but in your case you have to write like :
<?php echo $this->session->userdata('email'); ?>
If You are using flashdata, then You can get it using below code:
Controller
if (empty($this->session->userdata('UserID'))) {
$this->session->set_flashdata('flash_data', 'You don\'t have access!');
$this->load->view("initialHeader");
$this->load->view("login");
redirect('Login');
}
View
<?php if(!empty($this->session->flashdata('flash_data'))) {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('flash_data'); ?>
</div>
<?php } ?>
If You are using tmp data as a session, please refer below code:
Controller
<?php
if (!empty($data)) {
$this->session->set_userdata('permission_error_msg', $data);
$this->session->mark_as_temp('permission_error_msg', 10); // For 10 Seconds
$this->load->view('dashboard', array($title, $data));
} ?>
View
<?php if ($this->session->tempdata('permission_error_msg')) { ?>
<b class="login_error_msg"><?php
if (!empty($this->session->tempdata('permission_error_msg'))) {
echo $this->session->tempdata('permission_error_msg');
}
?></b>
<?php } ?>
Thank You.
Good day! I'm trying to make a forgot password function in the CodeIgniter framework but I'm getting 2 errors when i try to send the e-mail.
Some database info (I'm using phpMyAdmin):
Db name: kadokado
Db table name: users
Db email column: email
Db password column: wachtwoord
My controller file (Auth.php) :
<?php
class Auth extends CI_Controller{
public function forgot()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('forgot');
$this->load->view('templates/footer');
}else{
$email = $this->input->post('email');
$clean = $this->security->xss_clean($email);
$userInfo = $this->user_model->getUserInfoByEmail($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'We hebben dit email adres niet kunnen vinden');
redirect(site_url().'auth/login');
}
if($userInfo->status != $this->status[1]){ //if status is not approved
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
//build token
$token = $this->user_model->insertToken($userInfo->id);
$qstring = $this->base64url_encode($token);
$url = site_url() . 'auth/reset_password/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>A password reset has been requested for this email account</strong><br>';
$message .= '<strong>Please click:</strong> ' . $link;
echo $message; //send this through mail
exit;
}
}
public function reset_password()
{
$token = $this->base64url_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token is invalid or expired');
redirect(site_url().'auth/login');
}
$data = array(
'voornaam'=> $user_info->voornaam,
'email'=>$user_info->email,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('wachtwoord', 'Wachtwoord', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[wachtwoord]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('reset_password', $data);
$this->load->view('templates/footer');
}else{
$this->load->library('wachtwoord');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['wachtwoord']);
$cleanPost['wachtwoord'] = $hashed;
$cleanPost['user_id'] = $user_info->id;
unset($cleanPost['passconf']);
if(!$this->user_model->updatePassword($cleanPost)){
$this->session->set_flashdata('flash_message', 'Er is iets foutgegaan');
}else{
$this->session->set_flashdata('flash_message', 'Uw wachtwoord is geupdate, u kunt nu inloggen');
}
redirect(site_url().'auth/login');
}
}
}
My model file (User_Model.php) :
<?php
class user_model extends CI_model {
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function getUserInfo($user_id)
{
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$user_id.')');
return false;
}
}
public function insertToken($user_id)
{
$token = substr(sha1(rand()), 0, 30);
$date = date('Y-m-d');
$string = array(
'token'=> $token,
'user_id'=>$user_id,
'created'=>$date
);
$query = $this->db->insert_string('tokens',$string);
$this->db->query($query);
return $token . $user_id;
}
public function isTokenValid($token)
{
$tkn = substr($token,0,30);
$uid = substr($token,30);
$q = $this->db->get_where('tokens', array(
'tokens.token' => $tkn,
'tokens.user_id' => $uid), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
$created = $row->created;
$createdTS = strtotime($created);
$today = date('Y-m-d');
$todayTS = strtotime($today);
if($createdTS != $todayTS){
return false;
}
$user_info = $this->getUserInfo($row->user_id);
return $user_info;
}else{
return false;
}
}
}
?>
My view file (reset_password.php) :
<div class="col-lg-4 col-lg-offset-4">
<h2>Reset your password</h2>
<h5>Hello <span><?php echo $firstName; ?></span>, Voer uw wachtwoord 2x in aub</h5>
<?php
$fattr = array('class' => 'form-signin');
echo form_open(site_url().'auth/reset_password/token/'.$token, $fattr); ?>
<div class="form-group">
<?php echo form_password(array('name'=>'wachtwoord', 'id'=> 'wachtwoord', 'placeholder'=>'Wachtwoord', 'class'=>'form-control', 'value' => set_value('wachtwoord'))); ?>
<?php echo form_error('password') ?>
</div>
<div class="form-group">
<?php echo form_password(array('name'=>'passconf', 'id'=> 'passconf', 'placeholder'=>'Confirm Password', 'class'=>'form-control', 'value'=> set_value('passconf'))); ?>
<?php echo form_error('passconf') ?>
</div>
<?php echo form_hidden('user_id', $user_id);?>
<?php echo form_submit(array('value'=>'Reset Password', 'class'=>'btn btn-lg btn-primary btn-block')); ?>
<?php echo form_close(); ?>
</div>
And these are the errors I'm getting:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Auth::$user_model
Filename: controllers/Auth.php
Line Number: 123
Backtrace:
File: /home/ubuntu/workspace/application/controllers/Auth.php
Line: 123
Function: _error_handler
File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once
2nd error:
A PHP Error was encountered
Severity: Error
Message: Call to a member function getUserInfoByEmail() on a non-object
Filename: controllers/Auth.php
Line Number: 123
Backtrace:
I have absolutely no clue what I'm doing wrong and I hope someone can help me.
Thanks!
Load user model in auth controller. You can load it in constructor or in the function.
class Auth extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('user_model'); // load user model
}
public function forgot(){
// your code
}
In Function
class Auth extends CI_Controller{
public function forgot(){
$this->load->model('user_model'); // load user model
// your code
}
Not tested
You need to make sure that the user_model class is loaded from the controller. Like so:
class Auth extends CI_Controller {
function __construct() {
$this->load->model('user_model');
}
}
And be sure that you have the spelling/capitalization correct in the model class.
class User_Model extends CI_Model {
// rest of code
}
#frodo again.
First Error : in your controller code, you need to initialize model first than only you can use the model property.
public function forgot(){
// Changes required
$this->load->model('user_model');
$userInfo = $this->user_model->getUserInfoByEmail($clean);
}
Second Error :
if($userInfo->status != $this->status[1]){
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
How you get the value of $this->status[1] variable. You can simply use if($userInfo->status != true).
Please change this code and let me know if you have any error.
my validations are working ok but after that userid and password results empty in model fit_reg_model and it results into authentication failed.please help me out.
this is my code :
model fit_reg_model
`
class Ftg_reg_model extends CI_Model {
public function log_valid( $userid, $password )
{
$this->db->select("regID,loginCode");
$whereCondition = $array = array('regID' =>$userid,'loginCode'=>$password);
$this->db->where($whereCondition);
$this->db->from('fit_1login');
$query = $this->db->get();
////////////////////////////////checking values////////////////////
echo"<pre>";
print_r ($query->result()); exit;
return $query->row()->countID;
if( $query->num_rows() )
{
echo"<pre>";
print_r ($query->result()); exit;
return $query->row()->countID;
//return TRUE;
}
else
{
return FALSE;
}
}
}
contrller fit_ci
` public function fit_loguser()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('uname','User Id','required|valid_email|valid_emails|trim');
$this->form_validation->set_rules('password','Password','required|trim');
$this->form_validation->set_error_delimiters("","");
if($this->form_validation->run() )
{
$userid = $this->input->post('uname');
$password = $this->input->post('password');
//////////////////////////////////////loding model////////////////
$this->load->model('ftg_reg_model');
//echo $userid , $password;
if( $this->ftg_reg_model->log_valid('$userid','$password')== True )
{
//$this->load->view('fitasy/fit_userprofile');
$this->load->library('session');
$this->session->set_userdata('id',$id);
echo "Successful loged";
}
else
{
echo "Authentication failed";
}
}
else
{
$data['title'] = 'Fit';
$this->load->helper('form');
$this->load->view('fit/index.php',$data);
}
}
`
view fit_loguser
`
Login here to add items to your Cart
'form-horizontal'])?>
<?php echo form_error('uname'); ?>
<?php echo form_input(['name'=>'uname','class'=>'form-control','placeholder'=>'Username','value'=>set_value('uname')])?><br>
<?php echo form_error('password'); ?>
<?php echo form_password(['name'=>'password','class'=>'form-control','placeholder'=>'Password'])?><br>
<?php echo form_submit(['name'=>'logsubmit','class'=>'btn btn-default','value'=>'Proceed','type'=>'submit'])?>
<?php echo form_close()?><!-------------form close-------------------------------------->
</div>`
Try to remove
$this->db->select("regID,loginCode");
In your model to see what's happening
This question already has answers here:
CI - show database error or fail
(2 answers)
Closed 9 years ago.
I've developed a simple login system which works OK but fails, and I need to know why.
QUESTION: How to show what is causing the fail?
Here's the database function:
function login($email,$password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("users");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->username,
'user_email' => $rows->email,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
And here's the logic:
public function login()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('email', 'Your Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run() == FALSE)
{
$this->signin();
}
else
{
$email=$this->input->post('email');
$password=md5($this->input->post('pass'));
$result=$this->user_model->login($email,$password);
if($result)
{
$this->dash();
}
else
{
$data['title']= 'Login Error';
$this->load->view('nav/header', $data);
$this->load->view('login', $data);
$this->load->view('nav/footer', $data);
}
}
}
I know the error is happening as I redirect back to the login page if it fails and change the title text to show me (only in testing mode for right now). But how can I find out what is going wrong?
This is the check database function:
function login($email,$password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("users");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->username,
'user_email' => $rows->email,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
I assume all your php code is fine, then what you need is set custom form-validation-message for each input to know which input went wrong and echo them:
<?php echo validation_errors(); ?>
write below code in your view file
<section id="notification" >
<?php
if(validation_errors() !== '' ) {
echo "<div class='alert-msg error'>";
echo validation_errors();
echo "</div>";
}
$error = $this->session->flashdata('error');
$success = $this->session->flashdata('success');
if($error)
{
echo "<div class='alert-msg error'>";
echo $this->session->flashdata('error');
echo "</div>";
}
if($success)
{
echo "<div class='alert-msg success'>";
echo $this->session->flashdata('success');
echo "</div>";
}
?>
</section>
and set success/error message conditionally in flash data in controller ( see below)
if($result) {
$this->dash();
$this->session->set_flashdata('success', 'Login successfully.');
} else {
$this->session->set_flashdata('error', 'Login failed');
}
Read more Flashdata in CI
For your changed answer:
use below logic in your model
$qry = $this->db->get_where('users', array('username' => $this->_username ));
if ($qry->num_rows() == 1) {
$user = $qry->row_array();
$submitted_pass = md5($this->_password);
$db_pass = $user['password'];
if ($submitted_pass === $db_pass) {
return $user;
} else {
// wrong username/password
$this->session->set_flashdata('error', $this->errorList[10]);
return FALSE;
}
} else {
// no such username exist
$this->session->set_flashdata('error', $this->errorList[15]);
return FALSE;
}