Variable returning as undefined in codeigniter? - php

I am getting the following error message for each variable:
Message: Undefined index: on lines 59, 60, 61, 62
I cannot understand why as it is definitely getting the sessions data and also the databases are setup and their is a user which matches that criteria.
jobs.php(apply function):
public function apply(){
if($this->session->userdata('is_logged_in')){
$this->load->view('header');
$this->load->view('job');
$id = $this->session->userdata('id');
$query = $this->db->get_where('jobseeker_profiles', array('jobseeker_id' => $id));
$user = $query->row_array();
$points = $user['total_points_value'];
$name = $user['name'];
$email = $user['email'];
$jobseeker_profile_id = $user['id'];
$employer_profile_id = $this->input->post('employer_id');
$job_id = $this->input->post('job_id');
$this->db->set('jobseeker_profile_id', $jobseeker_profile_id);
$this->db->set('employer_profile_id', $employer_profile_id);
$this->db->set('job_id', $job_id);
$this->db->set('name', $name);
$this->db->set('email', $email);
$this->db->set('points_value', $points);
if($this->input->post('submit')){
$this->db->insert('applications');
}
redirect('applied-for');
}else{
redirect('login');
}
}
}
Hope fully you can help, thanks!

Have you checked if the 4 database variables you are setting in those lines are rightly declared in the table ? They have to match to work.

do some quick error checking directly from the controller or model like
// check if query did not come back
if ( ! $query = $this->db->get_where('jobseeker_profiles',array('jobseeker_id' => $id)) )
{ echo 'OMFG WHERE IS MY QUERY ???' ; }
else
{ $user = $query->row_array();
echo 'QUERY WORKED, User Name is:' . $user['name'] ;
}
and if this does not work, go back and make sure you are loading the database, that the user/password is correct, etc

Related

Trying to get property 'email' of non-object

I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.
A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/forms.php
Line Number: 26
Backtrace:
File:
E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
Line: 26 Function: _error_handler
File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
Function: require_once
Below is the controller
<?php
class Forms extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library('session');
$this->load->helper('url');
$this->load->model('user_model', 'auth');
}
public function forgot_pass()
{
if($this->input->post('forgot_pass'))
{
$email=$this->input->post('email');
$this->load->model('user_model', 'auth');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'E-mail', 'required');
if ($this->form_validation->run() == TRUE) {
$que=$this->db->query("select password,email from users where email='$email'");
$row=$que->row();
$user_email=$row->email;
if((!strcmp($email, $user_email)))
{
$pass=$row->password;
$to = $user_email;
$subject = "Password";
$txt = "Your password is $pass .";
$headers = "From: user#testdomain.com" . "\r\n" . "CC: hamza_zon#outlook.com ";
mail($to,$subject,$txt,$headers);
$this->load->view('user/header');
$this->load->view('user/confirm');
$this->load->view('user/footer');
}
else{
$data['error']="Invalid Email ID !";
}
}
else{
$data['error']="Email ID is required !";
}
}
$this->load->view('user/header');
$this->load->view('user/forgot_pass',#$data);
$this->load->view('user/footer');
}
}
?>
you should check before $user_email=$row->email; that the as per your criteria record exist or not, if row is not exist then you will get that error
so you should check as below
$row=$que->row();
if($row) {
$user_email=$row->email;
}
Try like this
$que = $this->db->query("select password,email from users where email=".$email);
if(isset($row) && $row != ''){
$txt = "Your password is" . $pass;
//Coding...
}
You need to handle it like this,
$query = $this->db->query("select password,email from users where email=".$email);
if ($query->num_rows() > 0) {
$row = $query->row();
$user_email = $row->email;
} else {
$user_email = '';
}
//then your next if condition in which you are comparing two strings
$row=$que->row();
$row is probably being returned as NULL or a falsy value.
var_dump($row) to check.
if(!$row)
{
die("user not found");
}
or
if(empty($row))
{
die("user not found");
}
Apply condition as, because in your case it may not getting the result from table for that email,
if (isset($row))
{
Note: row method returns a single result row. If your query has more than one row, it returns only the first row. The result is
returned as an object. Here’s a usage example:
$que=$this->db->query("select password,email from users where email like '$email'");
$row = $que->row();
if (isset($row))
{
$user_email = $row->email;
$user_password = $row->password;
}
Here is concise doc for the same.

Get int from column by using email to identify row

I want to get and echo a users permission level.
I have a function where the users email is passed, the function then needs to get the users permission level and return it, so it can be echoed on another page.
I imagine the function will look though the database for the passed email, it then finds the users permission and returns with that.
In the 'User.class.php'
public static function permGetter($email)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':permission'=>$permission]);
$user = $stmt->fetchObject('User');
if($user !== false)
{
return $permission;
}
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
In the 'permRequest.php'
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email))
{
echo 'Permission ' + (int) $permission;
}
}
else
{
//I use level 5 as a debug so i can see when it fails
echo 'Permission 5';
}
}
?>
Database
Here's an example on what my database looks like.
Edit 1
Okay messing about, I think i got closer to the solution.
First, #Lawrence Cherone, thanks for pointing out my mistake in my execute.
Okay I have changed my code in
User.class.php
public static function permGetter($email, $permission)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email');
$stmt->execute([':email'=>$email]);
$row = $stmt->fetch(PDO::FETCH_NUM);
$permission = $row['permission'];
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
I have made small changes to
permRequest.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
$permission = '';
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email, $permission))
{
echo 'Permission ', $permission;
}
}
}
?>
But now i get an error. The error is this Notice: Undefined index: permission in /classes/User.class.php on line 56
So, I read up on it and it seemed like it should be emptied first, so I empty it in permRequest.php that's why I'm passing it too, but I still get this error after i emptied it?
However if i change
$row = $stmt->fetch(PDO::FETCH_NUM);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);
/* OR */
$row = $stmt->fetch(PDO::FETCH_BOTH);
I get no error but it simply says my email or password is incorrect, which it isn't I have double and triple checked it.
So I'm confused to which PDO::FETCH_ I should use. I have read this (Click here) and I would say that both ASSOC, BOTH and NUM would fit the purpose.
So why is one giving an error while the two other's simply fails the login?
Edit 2
Found the solution and i have written it as a Answer. Can't accept it for the next two days however.
I moved everything out of the User.class.php and moved it into permRequest.php. This solved my problem for some reason. So my code looks like this now
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once("../includes/init.php");
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
if(Auth::getInstance()->login($email, $pass))
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sub = $row['permission'];
echo 'Permission ', $sub;
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
}
And I don't use the User.class.php for this function.
So my guess is something went wrong when returning $sub when it was in User.class.php

PHP Error, Undefined index error

In my codeigniter project I have this function in my model
function get_rtc_info($id)
{
$query = $this->db->get_where('rtc_info', array('id' => $id));
$query = $query->row_array();
$query = $query['id'].', '.$query['name'].', '.$query['address']; //line# 313
return $query;
}
I get the following error/warning when running the code
A PHP Error was encountered
Severity: Notice
Message: Undefined index: id , name and address
Filename: models/form_model.php
line number 313
I am not sure why I get this undefined index warnings. Can someone guide me on this error and how to resolve it. Thank you in advance
There are no rows in your table rtc_info. This is why you are watching this kind of notice. If you want, not show this notice check your variable with isset() before using
function get_rtc_info($id)
{
$query = $this->db->get_where('rtc_info',array('id' => $id));
$query = $query->row_array();
if(isset($query['id']) && isset($query['name']) && isset($query['address'])) {
$query = $query['id'].', '.$query['name'].', '.$query['address']; //line# 313
return $query;
}else{
return 'no data';
}
}
if these 3 fields are optional you may use following without else block
function get_rtc_info($id)
{
$query = $this->db->get_where('rtc_info',array('id' => $id));
$query = $query->row_array();
if(isset($query['id'])){
$row_id = $query['id'];
}else{
$row_id = 'no id';
}
if(isset($query['name'])){
$name = $query['name'];
}else{
$name = 'no name';
}
if(isset($query['address'])){
$address= $query['address'];
}else{
$address = 'no address';
}
$query = $row_id.', '.$name.', '.$address; //line# 313
return $query;
}
hope now clear

Using both MySQL procedure and session db in code igniter cause `2014` error

I have a controller like this:
$r_result = $this->storedprocedure->user_email_exist($in_email);
if($r_result->num_rows() == 1)
{
foreach ($r_result->result() as $row)
{
$salt = $row->salt;
$hash = $row->hash_password;
if(strcasecmp(Application_Helper::hash_password($aData['password'], $salt),
$hash)==0)
{
//Login success
echo('login success');
$newdata = array('user_id' => $row->id);
$this->session->set_userdata($newdata);
}
}
}
In the Storedprocedure model, is something like this:
public function user_email_exist($aEmail)
{
$r_result = $this->db->query("CALL user_email_exist('".$aEmail."')");
return $r_result;
}
I tested it, it can login success, but print an error:
A Database Error Occurred
Error Number: 2014
Commands out of sync; you can't run this command now
UPDATE ci_sessions SET last_activity = 1358764263, user_data =
'a:2:{s:9:\"user_data\";s:0:\"\";s:7:\"user_id\";s:2:\"35\";}' WHERE
session_id = '05e340b2aa6bd9b21261ed0d20354b3c'
Filename: libraries/Session.php
Line Number: 289
The problem is, I must use the MySQL procedure to implement the model layer, but it seems that have some conflict between the ci_session. Any recommend solutions for that issue? Thanks.
This error is caused due to the fact that mySQL Stored Procedures return MULTI RESULTS
even if there is only one select statement in them . Solution is to simply call $r_result->next_result() to loose the expected extraneous resultset.
I got the idea from this link.
please Replace the controller code like below:
$r_result = $this->storedprocedure->user_email_exist($in_email);
if($r_result->num_rows() == 1)
{
$row = $r_result->row_array();
$r_result->next_result(); // Dump the extra resultset.
$r_result->free_result(); // Does what it says.
$salt = $row->salt;
$hash = $row->hash_password;
if(
strcasecmp(Application_Helper::hash_password($aData['password'], $salt),$hash)==0
) {
//Login success
echo('login success');
$newdata = array('user_id' => $row->id);
$this->session->set_userdata($newdata);
}
}

Pulling data off of sql table with php using sessions

I'm trying to pull data off my sql table with php unique to the session's ID, however I only get the position that the user is in when I echo anything out!
<?php
include 'core/init.php';
$user_info = $_SESSION['user_id'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
displays as:
5 5
if I log in with the fifth position in the database!
The reason why you are getting 5 is for this code:
<?php echo $user_info['firstname'];?>
is that $_SESSION['user_id'] 's value is 5. So after the assignment $user_info's value is 5. Now because the $_SESSION['user_id'] is not set to an array as your intention seems to be. The result is that $user_info is taken as a string and ['firstname'] evaluates to [0]. If you like, you can update the ID 5 to 54, etc. You will always get the first character of your ID.
To correct this, try changing the last 2 lines before the return in your user_data function to:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
$data = array_merge(array($user_id), $data);
return $data;
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
}
to:
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$_SESSION['user_id'] = $user_data;
}
if (logged_in === true) {
should be
if (logged_in()) {
for me it seems like you forgot to update data in session.
lets say here:
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
$_SESSION = array_merge($_SESSION, $user_data);
}
hope it helps you to resolve your problems.
What I see that your in this line
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
you are using "firstname", whereas in database it is named as "first_name", see underscore
<h1><?php echo $user_info['first_name'];?>&nbsp<?php echo $user_info['first_name'];?> </h1>
Let me know if this solves or not as I too want to know its answer
May help you some changes in your code
function user_data($user_id) {
$data = array ();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`'. implode('`, `', $func_get_args). '`';
echo '<br>'.
$que = "SELECT $fields FROM `users` WHERE `id` = $user_id";
$data = mysql_fetch_assoc(mysql_query($que));
print_r ($data);
return $data;
}
}
function logged_in() {
return (isset($_SESSION['id'])) ? true : false;
}
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'firstname', 'email');
//$user_data = user_data($session_user_id, 'user_id', 'username', 'firstname', 'email');
print_r($user_data);
}
echo
$user_info = $user_data;//$_SESSION['user_id'];
?>
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
function user_data($data=array(),$whereData=array()) {
$str='';
if(isset($whereData) && is_array($whereData))
{
foreach($whereData as $key=>$val)
{
if($val!='')
if($str=='')
$str = $key." = '".$val."'";
else
$str .= " AND ".$key." = '".$val."'";
}
}
$condition =
$fields = implode(',' , $data);
if($str!=''){
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE $str"));
}
else
{
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` ));
}
return $data;
print_r ($data);
}
}
and
if (logged_in() === true) {
$data = array('username', 'first_name', 'last_name', 'email');
$where=array('user_id'=>$_SESSION['user_id'])
$_SESSION['data'] = user_data($data, $where);
}
and
<?php
include 'core/init.php';
$user_info = $_SESSION['data'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
From experience of creating large code bases in PHP and when you expand the application you will find you are using more and more data all over the place from the users table. Also, the table should only really contain the most vital data that is comonly used and you do NOT want to be sending more than 1 or 2 queries to the users table per page hit as it can soon become a bottle neck. For this reason you are better storing all of the data data (move large fields to another table or fields rarely used). Then store the whole user record in a session which means any function, class etc can use it as it becomes a superglobal and you can trust it enough to use it throughout the entire application without needed to re-query the users table again and again.
I have written a working example (suing your db table structure) and commented it all throughout explaining why i have done it the way i have and some points you might want to consider.
//change from user_data() to get_user_data() so we know we are "getting" it, makes it a little clearer
function get_user_data($user_id) {
//protect agains sql injections
$user_id = mysql_real_escape_string($user_id);
//you should also be using mysqli or PDO, not the outdated mysql library - just check the php documentation if you don't believe me ;)
$result = mysql_query("SELECT * FROM `users` WHERE `id` = '{$user_id}' LIMIT 1");
//only if the previous query returned a result do we want to fetch an array from it
if ($result) {
return mysql_fetch_assoc($result);
}
//query didn't work (syntax error for example) so return blank array
return array();
}
//start and restore the session
session_start();
//if first page hit, set the user details element
if (isset($_SESSION['user_details']) == false) {
$_SESSION['user_details'] = array();
}
//if already logged in, refresh their user details incase there were any changes
if (isset($_SESSION['user_details']->user_id)) {
//refresh the user data
$_SESSION['user_details'] = get_user_data($_SESSION['user_details']->user_id);
}
//login
if (empty($_POST['id']) == false) {
$_POST['id'] = trim($_POST['id']);
if (is_numeric($_POST['id'])) {
$_SESSION['user_details'] = get_user_data($_POST['id']);
}
}
//logout
if (isset($_GET['logout'])) {
if ($_GET['logout'] == session_id()) {
$_SESSION['user_details'] = array();
}
}
//see if logged in so we know what to display
if (empty($_SESSION['user_details'])) {
//not logged in
print "<form method='post' action=''><label>User ID</label><input type='text' name='id' value='5' /><input type='submit' value='Login' /></form>";
} else {
//is logged in
print "<a href='?logout=" . rawurlencode(session_id()) . "'>logout</a>";
}
//proof that it works
print '<pre>';
print_r($_SESSION['user_details']);
print '</pre>';
P.S. Also you may want to start using LIMIT in your SQL queries as LIMIT 1 in the query above tells mysql that it can stop searching after it finds 1 result - and you should have an index on that column (preferably a primary index or unique index) to keep it lightening fast (or at least in the beginning anyway >< ).

Categories