I am getting a foreach loop error in codeigniter, it was working fine, but once I moved the project to a new hosting I get an error for the loop. Both servers are using PHP 7.2
Here is the first error:
Message: array_slice() expects parameter 1 to be array, null given
And here is the second error:
Message: Invalid argument supplied for foreach()
The backtrace says the error is in the controller, I have checked many times and tried many methods but still the same.
Using is_array PHP function wont help, as it only hide the error messages, but the functions wont work as before.
Controller:
public function login(){
$data['title'] = 'Sign In';
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header', $data);
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// Get username
$username = $this->input->post('email');
// Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'id' => $user_id,
'email' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
// Set message
$this->session->set_flashdata('user_loggedin', 'Login Success');
redirect('users/account');
} else {
// Set message
$this->session->set_flashdata('login_failed', 'Login Faild');
redirect('users/login');
}
}
}
public function account($id = NULL){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$data['users'] = $this->user_model->get_users($this->session->userdata('id'));
$data['title'] = 'Account';
$this->load->view('templates/user_header', $data);
$this->load->view('users/account', $data);
$this->load->view('templates/user_footer');
}
Loop code:
<?php foreach (array_slice($users, 0, 1) as $user): ?>
<div><p><?php echo $user['first_name'] ?></p></div>
<?php endforeach; ?>
Model:
public function get_users($id){
$this->db->join('user_details', 'user_details.user_details_id = users.id');
$this->db->join('user_orders', 'user_orders.user_id = users.id');
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
Rewrite the below code:
<?php foreach (array_slice($users, 0, 1) as $user): ?>
<div><p><?php echo $user['first_name'] ?></p></div>
<?php endforeach; ?>
as:
<div><p><?php echo $users['first_name'] ?></p></div>
Because:
public function get_users($id){
$this->db->join('user_details', 'user_details.user_details_id = users.id');
$this->db->join('user_orders', 'user_orders.user_id = users.id');
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
This code will not return an multi-dimension array... you have used row_array() which will be a single array.
Related
When I use CodeIgniter session set_flashdata and insert data in database page going looping infinity. but without use set_flashdata it working fine perfectly.
$this->session->set_flashdata('success_msg', 'Successfully Inserted Settings');
redirect('admin/settings/sitesetting');
autoload
$autoload['libraries'] = array('database', 'form_validation', 'email', 'session', 'encrypt', 'user_agent','pagination','Pdf');
Controller
public function sitesetting()
{
$data['title'] = 'Admin - Site Settings';
$data['setting'] = $this->AdminModel->selectalldata('tbl_settings');
$set = $data['setting'];
if(isset($_POST['submisetting'])){
$this->form_validation->set_rules('setting_text', 'Setting ', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('admin/setting',$data);
}else{
$value = $set[2]->id;
$data = array( "setting_value"=> $this->input->post('setting_text'));
$update = $this->AdminModel->updatedata('tbl_settings', 'id', $value, $data);
$this->session->set_flashdata('success_msg', 'Successfully Inserted Settings');
redirect('admin/settings/sitesetting');
}
}else{
$this->load->view('admin/setting',$data);
}
}
Model
function updatedata($table_name, $where, $id, $data){
$this->db->where($where, $id);
$this->db->update($table_name, $data);
return true;
}
$this->session->set_flashdata("success_msg", "Successfully Inserted Settings");
redirect(''admin/setting',$data');
and then in view
session->flashdata('success_msg')): ?>
×
session->flashdata('success_msg'); ?>
This is my Users model
public function user_login($email, $password)
{
$this->load->library('session');
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get('users');
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data = array(
'id' => $row->id,
'username' => $row->username,
'email' => $row->email
);
$this->session->set_userdata($data);
}
return 1;
} else {
return false;
}
}
On my view i have a div to display the session username of the user
<div>
<?php echo $this->session->userdata('username'); ?>
</div>
It's does not appear What could be wrong?
When I print the contents of userdata() like this
<?php print_r($this->session->userdata()); ?>
I get the response
Array ( [__ci_last_regenerate] => 1502894606 )
simplify your query some
$data = $this->db->where(['email'=>$email, 'password'=>$password])->get('users')->row_array();
if($data){
$_SESSION['id'] = $data['id'];
$_SESSION['username'] = $data['username'];
$_SESSION['email'] = $data['email'];
return TRUE;
}
else{
return FALSE;
}
in view:
<div>
<?php echo $_SESSION['username']; ?>
</div>
try to print it out like this echo $data['username'] where $data is whatever variable you are sending to the view from the controller
If you actually have a username at line with
$row->username
Then right after that array, add
$this->load->vars( array('username' => $row->username) );
And in your view you would be able to get username
echo $username;
This is assuming you are not redirecting after setting your session.
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.
I'm new to CodeIgniter. My problem with my code is that, when a user logged in to his/her account, he can't view his/her details, instead, the detail of the first row from the table where I fetched it. I tried all of the accounts, but still the first row will show.
My goal is, when a user can log in, he will be redirected to his account with his details.
Controller
public function __construct()
{
parent::__construct();
$this->load->model('My_profile_model');
if(!$this->session->userdata('logged_in'))
{
// Set error
$this->session->set_flashdata('need_login', 'Sorry, you need to be logged in to view that area');
redirect('home/index');
}
}
public function show($teachers_id)
{
$user_id = $this->session->userdata('user_id');
$data['my_data'] = $this->My_profile_model->get_my_profile($teachers_id);
$data['title'] ='My Profile';
$data['nav_content'] = 'layouts/teacher_nav';
$data['main_content'] = 'teachers/my_profile';
$this->load->view('layouts/main', $data);
}
Model
<?php
class My_profile_model extends CI_Model{
public function get_my_profile($teachers_id)
{
$query = $this->db->get('teachers');
$this->db->where('teachers_id',$teachers_id);
return $query->row();
}
}
View
<h2 class="featurette-heading"><?php echo $my_data->first_name; ?> <?php echo $my_data->last_name; ?> <BR /><span class="text-muted"><?php echo $my_data->rank_id; ?></span></h2>
<hr>
<h4><small>Gender:</small> <?php echo $my_data->gender; ?></h4>
<h4><small>Status:</small> <?php echo $my_data->status; ?></h4>
<h4><small>Address:</small> <?php echo $my_data->address_id; ?></h4>
<h4><small>Field of Specialization:</small> <?php echo $my_data->fos_id; ?></h4>
<h4><small>School Graduated:</small> <?php echo $my_data->school_graduated; ?></h4>
<h4><small>Eligibility:</small> <?php echo $my_data->eligibilities; ?></h4>
<h3>Educational Qualification</h3>
<h4><small>Bachelors Degree:</small> <?php echo $my_data->bachelors_degree; ?></h4>
<h4><small>Masteral (Unit):</small> <?php echo $my_data->m_unit; ?></h4>
<h4><small>Years of Teaching Experience:</small> <?php echo $my_data->years_of_teaching; ?></h4>
Here, I will also include my login controller because I'm not sure if this controller returns a session.
users Controller
public function login()
{
$this->form_validation->set_rules('username','username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|min_length[4]|max_length[50]|xss_clean');
if($this->form_validation->run() == FALSE)
{
redirect('home');
}
else
{
//Get from post
$username = $this->input->post('username');
$password = $this->input->post('password');
$level = $this->input->post('level');
//Get user id from model
$user_id = $this->User_model->login_user($username, $password, 1, $level);
//Validate user
if($user_id <> 0)
{
//Create array of user data
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'level' => $level,
'logged_in' => TRUE
);
//Set session userdata
$this->session->set_userdata($user_data);
if ($level === 'Administrator') {
$this->session->set_flashdata('login_success', 'You are now logged in as an administrator');
redirect('admin/profiles');
}
if ($level === 'Teacher') {
$this->session->set_flashdata('login_success', 'You are now logged in as a teacher');
redirect('teacher/my_profile');
}
}
else
{
//Set error
$this->session->set_flashdata('login_failed', 'The login info that you entred is invalid. Please try again.');
redirect('home/index');
}
}
}
And the model for user controller
public function login_user($username, $password, $status, $level)
{
//Validate
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', $status);
$this->db->where('level', $level);
$result = $this->db->get();
if ($result->num_rows() == 1){
return $result->row(0)->teachers_id;
}
}
As I've said, I'm new to this. Any help will be appreciated.
Thanks in advance :)
Oh, got the answer now..
I just change the query of my model
public function get_my_profile($teachers_id = NULL)
{
$user_id = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('teachers');
$this->db->join('users','users.teachers_id = teachers.teachers_id');
$this->db->where('users.teachers_id',$user_id);
$query = $this->db->get();
return $query->row();
}