How to combine the $_SESSION into one variable in PHP mysqli ? - php

normally, i use the single $_SESSION for single field in the table as below in mysqli, let's say i use 'email' field in users table
$email = mysqli_real_escape_string($connect,$_POST["email"]);
$_SESSION['email'] =$email;
but it only can use email as sessions right ?
But what if i have multiple fields in the users table such as username, password, gender ?. How to combine/bind all the $_SESSION fields together into one variable ?
$user = $sessions_variable['username'];
thanks in advance :)

$_SESSON is an array. So your first move is to read up on arrays in the PHP manual.
After that you'll be able to either assign different values to different $_SESSON elements
$_SESSION['email'] = $email;
$_SESSION['username'] = $username;
or, after getting the user info from a database, assign it to a single element
$_SESSION['user'] = $row;

You can create multidimensional array in session like this
$_SESSION['user']['username'] =$username;
$_SESSION['user']['email'] =$email;
then you can pass whole user session array to single variable.
$user = $_SESSION['user'];

We can create multidimensional array for session follow the below procedure.
Example:
$_SESSION['foo']['foo_1'] =$foo1;
$_SESSION['foo']['foo_2'] =$foo2;
$_SESSION['foo']['foo_3'] =$foo3;
...
Now if we want to use whole foo array in single variable. you have to pass it like this.
$foo_whole_session = $_SESSION['foo'];
You can check what you found using print_r($_SESSION).

Related

PHP: How to store dynamic variables within session variable?

Here is what I'm trying to do:
$username = 'john';
$_SESSION['data'] = "Hello ".$username;
$username = 'mike';
$new = $_SESSION['data']; // trying make it like: $new = "Hello ".$username;
echo $new // should output: "Hello Mike"
I'm trying to save a phrase with a dynamic variable into a $_SESSION variable, so the phrase can later be change on a different page depending on the dynamic variable.
Is this possible, and how can it be done?
You could use string formatting for that. Take a look:
$username = 'John'; // not really needed for this test
$_SESSION['data'] = "Hello %s";
$username = 'Mike';
$text = sprintf($_SESSION['data'], $username);
echo $text
Output:
Hello mike
See the code in action here.
It will not work the way you have it written, because the value you have stored in the session is a completely new value made using the value of the $username variable. As soon as it has been created, the value in the session is not associated with the $username variable whatsoever.
You can store the name and the phrase in the session separately, so they can be modified independently, and then combine them together later at the time you need to use them together.
For the specific case in your comment, storing the SQL string for a prepared statement with placeholders should work.
$_SESSION['statement'] = "SELECT some_columns FROM some_table LIMIT ?, ?";
$_SESSION['limit'] = $limit;
$_SESSION['offset'] = $offset;
You can't store the prepared statement itself, but you can store the SQL string, and then prepare and execute it in subsequent pages.
$stmt = $pdo->prepare($_SESSION['statement']);
$stmt->execute([ $_SESSION['limit'], $_SESSION['offset'] ]);
Just remember when you are ready to bind values to it on your next page before executing it that you need to specify that they should be bound as integers or disable emulated prepared statements.
If you want to add new element in the session array then you can push new element in the session array as follows:
array_push($_SESSION['data'],$element)
You could do something like this:
$username = 'john';
$_SESSION['data'] = 'echo "Hello $username";';
$username = 'mike';
eval($_SESSION['data']);
But I don't know why you'd want to, there are millions of ways you could achieve the results you want, an approach like this probably isn't the best.

Session array not unset

I want to unset session array but It is not happening.
Where am I wrong in this?
if(isset($_SESSION['id']) && isset($_POST['processorder']))
{
$chk = $_SESSION['id'];
$query="update order_details set process_order='1' where id IN(".implode(',',$chk).")";
mysql_query($query) or die(mysql_error());
unset($chk);
}
$chk = $_SESSION['id'];
What you're doing here is creating a variable $chk with the value $_SESSION['id'] then unsetting this $chk but you've never touched the $_SESSION var.
To do so you need to have the following code :
$_SESSION['id'] = '';
unset($_SESSION['id']);
use php unset like that :-
unset($_SESSION['id']);
unset($_SESSION['processorder']);
or you can use session_destroy()
will delete ALL data associated with that user.
Not this unset($chk);
$chk is just a reference varialble. You need to unset the original variable.
unset($_SESSION['id']);
Use NULL and unset to remove the saved values in $_SESSION[] variables, like:
$_SESSION['id'] = NULL;
unset($_SESSION['id']);
If you put
$_SESSION['id'] = '';
and in case there is space in between '' two quotes, then
if(isset($_SESSION['id'])){}
returns true instead of false.
NOTE: You can also use session_destroy() function, but it destroy all saved session data.
Unsetting $chk doesn't actually affect the original array. You could use references to do that. But keep in mind that unsetting a reference itself doesn't affect the original array either. This should work:
$session = &$_SESSION;
unset($session[id']);
This could be useful if you need to perform a number of actions on the $_SESSION - should make your code a bit more readable

Map mysqli_fetch_assoc to object attributes?

I am using mysqli_fetch_assoc to get the database columns of one user (username, password, firstname, lastname ... ect).
I have these same columns as attributes in my user class. I was wondering if there is an easy way of mapping the values of the associated array to the object attributes everytime I call mysqli_fetch_assoc.
Something like this could work:
$user = mysql_fetch_assoc(...);
foreach($user as $key=>$value) {
$userObject->$key = $value;
}
Note the ->$key - this means to get the property referenced by the contents of the variable key.
Thank you #hjpotter92: mysqli_fetch_object() works perfectly, I just replaced my
$user = mysqli_fetch_assoc($user_set)
with
$user = mysqli_fetch_object($user_set)

Codeigniter Session - Access Userdata value for all users from DB

I am using Codeigniter's Session class to store session values in the database. Contained within the userdata field is the user's username and other values.
I want to get the username from each userdata field where the lastactivity is >= let's say 5 minutes.
The only way I can think to accomplish this is:
search for users active in last 5 minutes
get the userdata for each row returned
unserialise userdata
extract username
However this seems like the long way. Is there a cleaner/better way to do this?
Try this code.
$query = $this->db->select('user_data')->get('ci_sessions');
$user = array(); /* array to store the user data we fetch */
foreach ($query->result() as $row)
{
$udata = unserialize($row->user_data);
/* put data in array using username as key */
$user[$udata['user_name']] = $udata['user_role'];
}
from the result array, u can fetch needed information.

Storing all POST data in SESSION

I have more values (over 20) from $_POST like this...
$name = $_POST['name'];
$username = $_POST['username'];
$city = $_POST['city'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
NOTE : I have prevented there values from SQL injection.
My question is can I know is there a way to store all these POST values in SESSION at once?
Instead of this method..
$_SESSION['name'] = $name; etc
any answers will be highly appreciated.
Thank you.
$_SESSION['post-data'] = $_POST;
That will create an array of the post values in a single session variable. The values would be accessible as
$_SESSION['post-data']['name']
$_SESSION['post-data']['username']
...
You can add one array to another.
$_POST and $_SESSION are just arrays.
Note that the keys in the second array take priority in case of duplicates.
$_SESSION += $_POST;
However, I don't see this ending well, since the client side can inject anything he wants to the session, E.G. hijacking your users session id.
If you looking for session variables that are set using the same key as the posted array, you could use this:
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
This will make your $_POST array into variables based on the array key and also set the session at the same time. You could then access your name post by using either $_SESSION['name'] or $name.
This means you will not need to use: $name = $_POST['name']; anymore. As the above code will set the name variable for you and also set the session variable.
The best explanation of passing variables either with form post or header location redirection inside php check out my answer in this thread: How to pass variables received in GET string through a php header redirect?

Categories