I am trying to integrate phpass library with an existing authenticate method:
public static function authenticate($username, $password)
{
global $db;
$username = $db->prep_query($username);
$password = $db->prep_query($password); // Does not seems like it will be used
# First step: Retrieve the account based on the user input (email)
$query_string = "SELECT * FROM users WHERE email = '{$username}' LIMIT 1";
$query_result = static::find_by_query_string($query_string);
return !empty($query_result) ? array_shift($query_result) : false;
}
Now the record that comes back is ( according to print_r($query_result) )
Array ( [0] => User Object ( [id] => 7 [password] => $2a$08$qwSjSZ11TUYs5w1L89ppFer2n40HrnjlvaQ00DsUOOvjSYwoEmN4K [email] => test#user.com ) ) 1
What I'm trying to retrieve is: "$2a$08$qwSjSZ11TUYs5w1L89ppFer2n40HrnjlvaQ00DsUOOvjSYwoEmN4K"
But when I use $query_result[0][1] or $query_result[0]["password] I'm getting an error.
What am I missing here? How can I use the password value in $query_string array ?
You access the first array index, which happens to be an object. So you then need to access the property called password.
$query_result[0]->password
Related
Since moving session handling over to the database, the $_SESSION array doesn't seem to hold any values which I think is how sessions behave in PHP once the implementation is moved to DB.
This is causing quite a headache for me now. I'm not able to access the username of the user logged in via the details stored in the DB.
Here's my implementation of a function to retrieve the details of a user from the DB.
public function getUser($id, $db) {
$dbobj->query("SELECT * FROM SESSION WHERE id = $id);
$result = $dbobj->res();
return $result['data']['use'];
}
$result holds the values int he following format
array(1) (
[0 => array(3) (
[id => (string) 3fgg67bbsd77bVVgh
[access => (string) 14567893546
[data => (string) luser|s:5"Marke";
)
)
I would like $temp to hold the value "Marke". How should I parse the resultest returned?
I'd appreciate any help please.
resultset() function might be not exist.
So you can use this code:
public function getSessionUserName($id, $dbobj) {
$lcid = $id;
$dbobj->query("SELECT * FROM SESSION WHERE id = :sessid");
$dbobj->bind(':sessid', $lcid);
// execute query
$dbobj->execute();
// Commented this line
//$result = $dbobj->resultset();
// Use fetch() method
$result = $dbobj->fetch();
if ($result) {
//$temp= $result['data']['luser'];
$temp= $result['luser']
return $temp;
}
}
$result will generate following type of output (Output will be based on fields ):
Array
(
[id] => 3fgg67bbsd77bVVgh
[0] => 3fgg67bbsd77bVVgh
[access] => 14567893546
[1] => 14567893546
[luser] => Marke
[2] => Marke
)
So I started to get a little more practice in php and want to create a object oriented forum. Therefor I want to have a Database class such like:
<?php
class Database {
public $databaseConnection;
function __construct(){
$this->databaseConnection = new PDO('sqlite:test.sq3', 0, 0);
$this->databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$params = NULL;
$pdoStatement = $this->databaseConnection->prepare('CREATE TABLE IF NOT EXISTS user(
id INTEGER PRIMARY KEY,
username VARCHAR(40) NOT NULL UNIQUE,
numberoflogins INTEGER DEFAULT 0,
bannedstatus BOOLEAN DEFAULT FALSE,
dateofjoining TIME
)');
$pdoStatement->execute(array_values((array) $params));
}
function query($sql, $params = NULL){
$s = $this->databaseConnection->prepare($sql);
$s->execute(array_values((array) $params));
return $s;
}
function insert($table, $data){
self::query("INSERT INTO $table(" . join(',', array_keys($data)) . ')VALUES('. str_repeat('?,', count($data)-1). '?)', $data);
return $this->databaseConnection->lastInsertId();
}
}
Then I do this in the same script:
$database = new Database();
$database->insert('user',array( 'id' => 0,
'username' => 'gulaschsuppe',
'numberoflogins' => 23,
'bannedstatus' => TRUE,
'dateofjoining' => time()));
$searchID = 0;
$userData = $database->query('SELECT username FROM user WHERE id = 0');
$username = $userData->fetchAll();
print_r(array_values($username));
?>
I just wanted to see how things working. The most important part of the code is the class. I needed a little bit time to figure out how I get the information I wanted. This is what I get.
Array ( [0] => Array ( [username] => gulaschsuppe [0] => gulaschsuppe ) )
Everythings working, but I donĀ“t think this is best way to get the informations. I get an Array with an Array. Also, now there is no validation but first I want to focus on the functions query and insert.
So, can you explain how the last part with username => g. [0] => g. occured ?
I would like to know how I can improve the functions and please tell me when I do something totally wrong.
Array (
[0] => Array (
[username] => gulaschsuppe
[0] => gulaschsuppe
)
)
You're getting the result with both names columns (so you could do $row['username']) and numerically (so you can do $row[0]). This is the default PDO behavior. You need to use the PDO::FETCH_* constants in order to change the fetched results. PDO::FETCH_BOTH is the default value.
You can either set it when you're fetching:
$username = $userData->fetchAll(PDO::FETCH_ASSOC);
Or globally at some point:
$this->databaseConnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
In the case that you want only a single column, you can use this fetch mode:
$usernames = $userData->fetchAll(PDO::FETCH_COLUMN);
// $usernames = array('gulaschsuppe');
This fetches only a single column for each row, without wrapping each result in another array (column 0 is fetched by default).
See the PDOStatement::fetch() documentation for more details.
i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.
I'm trying to work with the form dropdown function for the codeigniter form helper.
echo form_dropdown('userCharacters', $userRoster, '', '', 'id="userCharacter"');
If you notice the $userRoster is the array I pass from the controller to the view.
Here's how it shows up when I do a print_r on the array.
Array
(
[0] => stdClass Object
(
[id] => 1
[rosterName] => Kid Wonder
)
[1] => stdClass Object
(
[id] => 3
[rosterName] => Oriel
)
)
However I am getting these errors and not sure why
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: helpers/form_helper.php
Line Number: 352
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: helpers/form_helper.php
Line Number: 352
EDIT :
Array
(
[0] => Array
(
[id] => 1
[rosterName] => Kid Wonder
)
[1] => Array
(
[id] => 3
[rosterName] => Oriel
)
)
EDIT 2 :
What's supposed to happen is after the user logs in it has the default character id and the role id of the user that is held in the userData array. It runs the library function getRosterList. Inside that function it checks to see if the user has a role id of 4(admin) or 5(superadmin) and if they are then what I want it to do is get ALL the roster members which would include their default character and have it as the selected option. If they are not one of those two roles then I just want it to get the roster members that they control and have the preselected option as the default character id. And if they only have one character then it displays a h1 tag instead of the dropdown.
Controller:
$this->data['userData'] = $this->users->getUserByUserID($this->session->userdata('userID'));
$this->data['userRoster'] = $this->kowauth->getRosterList($this->data['userData']->usersRolesID);
Library (kowauth)
* Get roster list
*
* #param integer
* #return object/NULL
*/
function getRosterList($usersRolesID)
{
// Check args
if(!is_numeric($usersRolesID)) { throw new Exception('Non-numeric $usersRolesID provided to getRosterList()'); }
if (($usersRolesID == 4) || ($usersRolesID == 5))
{
return $this->ci->users->getAllRoster();
}
else
{
return $this->ci->users->getRosterByUserID($this->ci->session->userdata('userID'));
}
}
Model:
/**
* Get roster list
*
* #return object/NULL
*/
function getAllRoster()
{
$this->db->select('id');
$this->db->select('rosterName');
$this->db->select('rosterStatusID');
$this->db->from('rosterList');
$this->db->order_by('rosterName');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
return null;
}
/**
* Get list of roster by user ID
*
* #return object/NULL
*/
function getRosterByUserID($userID)
{
// Check args
if (!is_numeric($userID)) { throw new Exception('Non-numeric $userID provided to getRosterByUserID()'); }
$this->db->select('id');
$this->db->select('rosterName');
$this->db->from('rosterList');
$this->db->where('userID', $userID);
$this->db->order_by('rosterName');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result_array();
}
return null;
}
View:
<?php
echo '<pre>';
print_r($userRoster);
echo '</pre>';
if (count($userRoster) == 1)
{
echo '<h1>'.$userRoster->rosterName.'</h1>';
}
else
{
$options = array (
$userRoster['id'] => $userRoster->rosterName
);
echo form_dropdown('userCharacters', $options, '', 'id="userCharacter"');
}
?>
Anybody have any ideas on this?
You're currently passing an array of objects. I believe that your $userRoster array should be formatted like this:
Array
(
1 => 'Kid Wonder'
3 => 'Oriel'
)
Also, I believe that form_dropdown only takes four parameters and you're trying to pass it five. You might want to move that last argument into the fourth spot:
echo form_dropdown('userCharacters', $userRoster, '', 'id="userCharacter"');
Should produce:
<select name="userCharacters" id="userCharacter">
<option value="1">Kid Wonder</option>
<option value="3">Oriel</option>
</select>
Which I think is what you're going for!
http://codeigniter.com/user_guide/helpers/form_helper.html
I am creating a notification class which uses the session to store messages. I need to create them as a multidimensional array, so I can take advantage of different 'namespaces', so as to keep messages from displaying on the wrong pages.
Here is an example:
print_r($_SESSION)
Array
(
[EVENT_CMS] => Array
(
[Notifier] => Array
(
[0] => 'Your settings have been saved.'
[1] => 'You must re-upload...'
)
)
)
Now on the settings page, these messages will print with a call to the proper method.
I am having trouble setting up the message container within the class. This is what my constructor looks like:
public function __construct($namespace = 'Notifier') {
$this->_session_start();
if(defined('SESSION_NAMESPACE')){
$this->notifications =& $_SESSION[SESSION_NAMESPACE][$namespace];
} else {
$this->notifications =& $_SESSION[$namespace];
}
}
(The SESSION_NAMESPACE constant is defined, so the true block is executed.)
$Notify = new Notifier();
$Notify->add($_GET['test']);
print_r($_SESSION);
The above code yields me this array:
$_SESSION
Array
(
[EVENT_CMS] => Array
(
[Notifier] => 1
)
)
The add message method should update the session, right? Since the notifications array is a reference? The call to update_session() has no effect on the output...
public function add($message, $class = NULL) {
$message_node = $message;
$this->notifications[] = $message_node;
$this->update_session();
}
public function update_session(){
$this->SESSION[$this->namespace] &= $this->notifications;
}
You are mixing up the bitwise operator with the reference operator. The wrong one is used in your update_session() method.