Codeigniter: Get userdata from another table using session - php

I'm trying to print userdata from another table with session. The table with the session is "userlogin" while the table with the data is "userinfo"
Here's what I've done so far
Controller
public function index()
{
if ( $this->session->userdata('logged_in') )
{
$session_data = $this->session->userdata('userinfo');
$id = $session_data['id'];
$this->load->model('Userdata_model');
$result = $this->Userdata_model->get_user_data3($id);
if($result==0)
{
echo 'No user Found';
}
else
{
$data['id']=$result;
$this->load->view("userdata_view", $data);
}
}
}
Model
public function get_user_data3($id)
{
if (isset($this->session->userdata['logged_in'])) {
$userid = ($this->session->userdata['logged_in']['id']);
} else {
header("location: http://localhost/test");
}
$query = $this->db->query("SELECT * FROM userinfo WHERE id='$id'");
foreach ($query->result_array() as $row)
{
echo $row['fName'];
echo $row['phone'];
}
}
View
<?php foreach ( $query->result_array as $new_user )
{
?>
<h4>Your name: <?php echo $new_user['fName'] ?> </h4>
<?php
}
?>

change function in controller :
public function index()
{
if ( $this->session->userdata('logged_in') )
{
$session_data = $this->session->userdata('userinfo');
$id = $session_data['id'];
$this->load->model('Userdata_model');
$data['result'] = $this->Userdata_model->get_user_data3($id);
$this->load->view("userdata_view", $data);
}
}
change model function like:
public function get_user_data3($id)
{
$query = $this->db->query("SELECT * FROM userinfo WHERE id='$id'");
return $query;
}
and view :
<?php if($result->num_rows() == 0){
echo 'No user found';
}
else {
foreach ( $result->result_array() as $new_user ){ ?>
<h4>Your name: <?php echo $new_user['fName'] ?> </h4>
<?php }
}
?>

Related

passing user information to view in codeigniter

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.

login form submit results in authentication failed in codeigniter 3.1.2

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

in php table tag not working

I want the table tag to come before the display of records in cart() function but it is being displayed after it rather?
How to correct that and in cart() function in the display of records when I am trying <tr> and <td> tags to display its not working
<?php
session_start();
$page = 'index.php';
$connection = mysqli_connect("localhost","root","","cart");
if(isset($_GET['add']))
{
if(array_key_exists('cart_'.$_GET['add'], $_SESSION))
$_SESSION['cart_'.$_GET['add']]+= 1;
else
$_SESSION['cart_'.$_GET['add']] = 0;
header("Location: cartindex.php");
}
if(isset($_GET['remove']))
{
$_SESSION['cart_'.$_GET['remove']]--;
header("Location: cartindex.php");
}
if(isset($_GET['delete']))
{
$_SESSION['cart_'.$_GET['delete']]=0;;
header("Location: cartindex.php");
}
function cart()
{
global $connection;
$total = 0;
?>
<table class="table table-striped"><tr><th>ID</th><th>Name </th><th>Price Per Item</th><th>Cost</th><th>Add</th><th>Substract</th><th>Delete</th></tr>
<?php foreach ($_SESSION as $key => $value) {
if($value > 0)
{
$id = substr($key,5,strlen($key)-1);
$result = mysqli_query($connection ,'select id,name,price from products where id ='.$id);
while($row = mysqli_fetch_assoc($result))
{
$cost = $row['price'] * $value;
echo $row['id'].' '.$row['name'].'#'.$row['price'].'*'.$value.'='.$cost.'[+]'.'[-]'.'[delete]'.'<br>';
$total = $total + $cost;
}
}
}
?></table><?php
if($total==0)
{
///
}
else
{
$dis="'payment made'";
echo 'Total cost is '.$total.'<br>';
echo '<br><button type="button" class="btn btn-success" onclick="alert(\'Payment accepted\');">Success</button>';
}
}
function product()
{
$connection = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
die("not connected to db ".mysqli_connect_error());
}
$get = mysqli_query($connection , "select id,name,description,price from products where quantity > 0 order by id DESC");
while($row = mysqli_fetch_assoc($get))
{
echo '<div class="boxed">'.$row['name'].'<br>'.$row['price'].'<br>'.$row['description'].'<br>ADD'.'<br>'.'</div>';
}
}
?>
Try replace "echo" with "return" inside functions.

how to query two tables from database and show the result in a single row using codeigniter

I have two tables One for users and the other for project listing
My problem is that i want to display each project(from project_table)and email belonging to user who listed the project(from user_table) on a single row
The project_table has a row for user_id(i.e id from user_table that identifies the user who posted the project)
here's my view(project_view):
I this case im displaying data from project_table but i want to display email for a particular user from user_table
<?php
foreach($query as $row)
{
?>
<p> <?echo $row->pro_name ?></p>
<p> <?echo $row->duration ?></p>
<p> <?echo $row->budget ?></p>
<p>User email will be displayed here</p>
<?
}
my model:
function get_projects()
{
$query = $this->db->get('project_table');
return $query->result();
}
my controller:
function show_projects()
{
$data['query']=$this->project_model->get_projects();
$this->load->view('project_view', $data);
}
Any ideas on how to implement this will be much appreciated
You can use joined query in your model
function get_projects()
{
$query =$this->db->select('p.*,u.email')
->from('project_table p')
->join('user_table u','p.user_id = u.id')
->get();
return $query->result();
}
And in your view you can do so
<?php
foreach($query as $row)
{
?>
<p> <?php echo $row->pro_name; ?></p>
<p> <?php echo $row->duration; ?></p>
<p> <?php echo $row->budget; ?></p>
<p><?php echo $row->email;?></p>
<?php
}
?>
I would rewrite controller and model function to allow for a user parameter:
function get_projects($user=null)
{
if ($user == null){
$query = $this->db->get('project_table');
}else{
$query = $this>db->get('project_table')->where('user_id',$user);
}
return $query->result();
}
function show_projects($user)
{
$data['query']=$this->project_model->get_projects($user);
$this->load->view('project_view', $data);
}
Now you can call your controller with a user parameter
http://..../show_user/1
1st approach is JOINs
$this->db->select('project_table.* as project, user.id as user_id, user.email as email')
->from('project_table')
->join('user', 'project.id = user_id');
$result = $this->db->get();
2nd not recommended
function get_projects()
{
$query = $this->db->get('project_table');
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function get_email($id = FALSE) {
if ($id === FALSE) return FALSE;
$query = $this->db->get_where('user', array('user_id' => $id));
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
somewhere in controller...
if (!$projects = $this->model->get_projects()) {
foreach ($projects as $key => $project) {
# code...
$projects[$key]->user_email = $this->model->get_email($project->user_id);
}
//projects is now with user_email field
$this->load->view()...
} else {
//no data recieved
redirect(); //redirect to default_controller
}
Try join this -
1) Model
function get_projects()
{
$this->db->select('*');
$this->db->from('project_table');
$this->db->join('user_table', 'project_table.user_id = user_table.id');
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query->result();
}
}
2) Controller
$data['user_project'] = $this->project_model->get_projects();
$this->load->view($view, $data);
3) View
foreach($user_project as $row)
{
echo "<p>" .$row->pro_name. "</p>";
echo "<p>" .$row->duration. "</p>";
echo "<p>" .$row->budget. "</p>";
echo "<p>" .$row->email. "</p>";
}

Cookies and variables

I've created a login class for my web app and it does work, but now I've created that infamous "keep me logged in" - checkbox and don't get it to work. Here's my class for login:
<?php
error_reporting(E_ALL ^ E_NOTICE);
class Login {
private $error;
private $connect;
private $email;
private $password;
public $row;
public function __construct(PDO $connect) {
$this->connect = $connect;
$this->error = array();
$this->row = $row;
}
public function doLogin() {
$this->email = htmlspecialchars($_POST['email']);
$this->password = htmlspecialchars($_POST['password']);
$this->rememberme = $_POST['rememberme'];
if($this->validateData()) {
$this->fetchInfo();
}
return count($this->error) ? 0 : 1;
}
public function validateData() {
if(empty($this->email) || empty($this->password)) {
$this->error[] = "Täyttämättömiä kenttiä";
} else {
return count($this->error) ? 0 : 1;
}
}
public function fetchInfo() {
$query = "SELECT * FROM users WHERE email = :email AND activation_token IS NULL";
$stmt = $this->connect->prepare($query);
$stmt->execute(array(
':email' => $this->email,
));
if($stmt->rowCount() == 0) {
$this->error[] = "Väärä käyttäjätunnus tai salasana";
return 0;
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['name'];
$_SESSION['profilepic'] = $row['profilepic'];
if(isset($this->rememberme)) {
setcookie("loggedin", "yes", time() + 25200);
}
}
if (Register::cryptPass($this->password) != $row['password']) {
$this->error[] = "Virheelliset kirjautumistiedot";
} else {
return true;
}
return count($this->error) ? 0 : 1;
}
public function displayErrors() {
if(!count($this->error)) return;
echo "<div class='login_error'>";
foreach($this->error as $key=>$value) {
echo "<p>".$value."</p>";
}
echo "</div>";
}
public function doLogout() {
session_destroy();
}
}
?>
And here's a small part of my code from my another file where I'm checking if the session or cookie is set:
<?php
if (isset($_SESSION['email']) || isset($_COOKIE['loggedin'])) {
?>
<div id="header_container_isloggedin">
<div class="container_12">
<header id="header">
<div class="grid-12">
<ul id="menu">
<li class="profile-name">
<a href="profile.php?id=<?php echo $_SESSION['user_id']; ?>">
<span class="header_username">
<img src="images/thumbnails/<?php echo $_SESSION['profilepic']; ?>"
class="profile_evensmaller"/>
<span class="header_name"><?php echo $_SESSION['name']; ?></span></span></a>
</li>
</ul>
<?php } ?>
The problem is that everytime the cookie is set, it doesn't display my profile picture or name since they've saved inside of $_SESSION variable. So how should I approach this and get this to work. I know that right now it's not the safest method, since I'm not generating any hashes for that cookie, but right now the only thing I'm interested in, is to get this one to work.

Categories