Assign value to variable inside Function - php

I have a function as stated below. But, I'm not sure on how to assign the values roles from database in the variable. Because I need the values roles' to decide either the user is admin or not. Velow is my code.
function find_user_by_username(string $username){
//find users in the database acourding to Input
$sql = 'SELECT username, password, roles from users WHERE username=:username';
$statement = dbConnect()->prepare($sql);
$statement->bindValue(':username', $username, PDO::PARAM_STR);
$statement->execute();
return $statement->fetch(PDO::FETCH_ASSOC);
}
Kindly advise. Thanks.

The best method is to save the required information in the session when logging in.
Or use the following code:
$result = find_user_by_username($username) ;
if ($result["roles"] == 'admin'){}

Related

PHP Update datetime with session

I use the following to update when a user logs in.. but this only works if they log in.. I have a remember me function and if checked user does not have to login.. and then it don't update..
is there a way to use the users session ID to update the last activity?
$stmt = $db->prepare("UPDATE users SET DateLastVisit = ?");
$stmt->bind_param('s', $Date);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
To accomplish this, you will need to match the activity with the user id as without this, you will end up updating every users record.
Try this:
if(!isset($_SESSION)){//check if we already have a session at the moment
session_start();
}
$user_id = $_SESSION['id'];//change to your session id key
$stmt = $db->prepare("UPDATE users SET DateLastVisit = ? WHERE id_user = ?");//change id_user to what you have in your database
/*always check whether the prepare() succeeded */
if ($stmt === false) {
trigger_error($db->error, E_USER_ERROR);
}
$stmt->bind_param('si', $Date, $user_id); // we bind the user_id as well
$stmt->execute(); //execute, returns true/false
$result = $stmt->get_result();
$stmt->close();
when user login,set a token for this user,and give this token TTL,save this to your table.then,you can check user login state with token,once ttl expired,rebuild a new token and ttl.

SQL Query username:password

Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)
If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();
I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);
You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.
$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)

Obtaining an specific db value

I'm using PDO for a connection into my db. There, I have a table where I store the users. In that table I have 5 columns: id, username, password, mail and sex.
What I really want is to store in a SESSION variable, the sex of the user that has been logged in. I don't know exactly what to use, because all the examples that I've seen, are usually for printing all the results of the db into the webpage with a foreach statement, but that isn't what I want.
Actually, this is the code that I have:
$connection = new PDO('mysql:host=localhost;dbname=db', "user", "password");
$sql = 'SELECT * FROM users WHERE username = :username AND password = :password';
$statement = $connection->prepare($sql);
$statement->bindParam(':username', $_POST['username'], PDO::PARAM_STR, 12);
$statement->bindParam(':password', $_POST['password'], PDO::PARAM_STR, 30);
$result = $statement->execute();
if ($result) {
$result = $statement->fetchAll();
if (!empty($result)){
$_SESSION['login'] = true;
$_SESSION['username'] = $_POST['username'];
echo 'Hello '.$_POST['username'].', you have been connected successfully.';
}
else {
echo 'Sorry, this user do not exist.';
}
}
So, this is correctly working.
But now, what I want is to store the sex value from the db in a $_SESSION['sex'] variable. How can I do that?
Thanks.
You can just add in the session after username, you have already slected from your query
$_SESSION['username'] = $_POST['username'];
$_SESSION['sex'] = $result[0]['sex'];
You might want to remove $result from query execution, so this line
$result = $statement->execute();
Will be
$statement->execute();
Just assign it from the result row:
$_SESSION['sex'] = $result[0]['sex'];
You have to use [0] because you used fetchAll, which returns a 2-dimensional array of rows and columns.

Trying to display user information after they login

I'm trying to display a users information on a profile page after they get logged in. Here is the code I'm using:
<?php
require_once('connection.inc.php');
$conn = dbConnect('read');
// get the username's details from the database
$sql = ("SELECT firstname, lastname FROM members WHERE username ='".$_SESSION['username']."'");
$_SESSION['firstname'] = 'firstname';
$_SESSION['lastname'] = 'lastname';
// initialize and prepare statement
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
// bind the result,
$stmt->bind_result($_SESSION['firstname'], $_SESSION['lastname']);
$stmt->execute();
$stmt->fetch();
The code runs without any errors but on the profile page the results get displayed as:
firstname: firstname
lastname: lastname
instead of plugging in the information that was supposed to be pulled from the database.
The display code on the profile page itself is correct, because I can set the session variables above from the user login page, and they work properly. I just don't want to be pulling in all that information at login, if the user isn't going to be doing anything with it. Thanks for any help.
Citation from the php manual:
Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
see http://php.net/manual/en/mysqli-stmt.bind-result.php
So just put it that way:
$stmt->execute();
$stmt->bind_result($_SESSION['firstname'], $_SESSION['lastname']);
$stmt->fetch();
Okay, there are a number of issues regarding your code.
As artiifix already mentioned, you can only bind the results after you've executed the query. It is, however, better to use prepared statements using parameters.
Also, you set $_SESSION['firstname'] to firstname and $_SESSION['lastname'] to lastname, which is why you get that output. You can remove those lines of code.
<?php
require_once('connection.inc.php');
$conn = dbConnect('read');
// get the username's details from the database
$sql = "SELECT firstname, lastname FROM members WHERE username=?";
/* See this? I've put a parameter in the query.
* You need to do this in order to prepare a statement.
*/
// initialize and prepare statement
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
// Bind parameters and execute the query
$stmt->bind_param("s", $_SESSION['username']);
$stmt->execute();
// Next, bind the results to the variables.
$stmt->bind_result($_SESSION['firstname'], $_SESSION['lastname']);
$stmt->fetch();
[...]
Furthermore, if above code is the top of your php-script, you would need to open the session to access the session variables!
<?php
session_start();
require_once('connection.inc.php');
$conn = dbConnect('read');
[...]
And, to simplify things even more: if the user is already logged in, and the session variables are already set, there is no need to fetch them again.
<?php
session_start();
echo $_SESSION['firstname'] . ' ' . $_SESSION['lastname'];
[...]

Retrieving a single fetch value from a function using PHP

//This is my function in retrieving the id of the user base from its email and pass. this is for functions.php
function getID($email,$pass)
{
$pdo = new PDO(connection here);
$stmt = $pdo->prepare('SELECT id user where email = :email and pass = :pass LIMIT 1');
$stmt->execute(array(':email'=>$email, ':pass'=>md5($pass)));
$result = $stmt->fetch();
return $result['id'];//Is this the right way of returning a value from a fetch value?
}
//this is for user.php.
include 'function.php';
session_start();
$_SESSION['id'] = getID($_POST['email'],$_POST['pass']);
Is this the right way of retrieving it? but i do not get any values from it. Need help thanks!
Your query is missing a FROM.
SELECT id FROM user WHERE email = :email AND pass = :pass LIMIT 1

Categories