Warning: Illegal string offset - php

I'm trying to set session in my program, after the user has logged with his account. If user input good email and password, then program set some variables, like this:
$_SESSION['user']['id'] = $row['id'];
$_SESSION['user']['email'] = $email;
$_SESSION['user']['admin'] = $row['admin'];
$_SESSION['logged'] = true;
The problem is, that I'm getting this warning from first three rows of code above:
Warning: Illegal string offset 'id' in C:\Program Files (x86)\Zend\Apache2\htdocs\OOPeshop\user\User.php on line 193
So I checked, if all the variables are set, so i add to my code this two lines:
var_dump($row);
var_dump($email);
but it was looking alright, I was getting output
array(2) { ["id"]=> string(2) "14" ["admin"]=> string(1) "0"}
string(22) "foobar#gmail.com"
So can someone explain me where is the problem? I checked similar question, but found no solution to my problem.
I have tried this:
$user = array('id' => $row['id'], 'email' => $email, 'admin' => $row['admin']);
$_SESSION['user'] = $user;
No more warnings. It set array first and then set whole array to session variable, it worked, but i don't know where's problem in my first code, so maybe someone with better understanding can explain it better.

I have tried this:
$user = array('id' => $row['id'], 'email' => $email, 'admin' => $row['admin']);
$_SESSION['user'] = $user;
No more warnings. It set array first and then set whole array to session variable, it worked, but i don't know where's problem in my first code, so maybe someone with better understanding can explain it better.
It seems that $_SESSION['user'] has been in somehow set to string, dont know why, but that's the only explanation.

This type of error can be couse of attempt to access an array index using an object or an array as the index key. Check whether your array is proper.

Try this:
Somewhere in the begininig of your code
if(!isset($_SESSION['user'])){
$_SESSION['user'] = array();
}
Then you can continue adding elements for $_SESSION['user'] as you did ( $_SESSION['user']['id'] = ... )

Related

Unserialize not working in php 5.5.26

I had a function that took the serialized data, turned into array, added to the array to then push it back to the MySQL DB perfect....in php 7. When I uploaded for a client they have php 5.5.26 and now its not working. It looks like the unserialized variable still has a string, not array so it doesnt add to it.
What was working in php 7
$dashboard = DB::queryFirstField("SELECT dashboard_array FROM compel_dashboard
WHERE user_id = %i", $user_id);
$array = unserialize($dashboard);
array_push($array, $dashboard_item);
$query = DB::update('compel_dashboard', array(
'dashboard_array' => serialize($array)
), "user_id=%s", $user_id);
Whats going on:
$dashboard contains string(27) "s:19:"dashboard-recommend";"
$array contains string(19) "dashboard-recommend"
So obviously I cant push_array to a string. Whats going on? Why would this work with PHP 7?

accessing session array data, deleting or changing one of the variables within this array

Here is my session array:
Array ( [username] => dog#dog.net [tmpPayment] => Array ( [mID] => 48 [item_1_amt] => 35.00 [description] => Student ) )
I created the ['tmpPayment'] array with the following code:
$tmpPayArr = array();
$tmpPayArr = array('mID'=>$mID,'item_1_amt'=>'35','description'=>'student');
$_SESSION['tmpPayment'] = $tmpPayArr;
I have looked for a simple answer to three questions: (1)how do I add a variable to the [tmpPayment] array (2)how do I change the value of [amount] variable within the [tmpPayment] array (3)how do I remove/delete the [tmpPayment] array altogether. (4)how do I assign the value of ['tmpPayment']['mID'] to a new variable $memberID. For (3) I have unsuccessfully tried:
unset($_SESSION['tmpPayment']);
I think my main problem is not understanding how to REFERENCE the array and its variables properly.
UPDATE:
I have successfully added and change my SESSION variable with the following:
$_SESSION['tmpPayment']['item_1_amt'] = $x_amount;
$_SESSION['tmpPayment']['description'] = $x_invoice_num;
Is this best practice?
Still need help with (3)...removing the session variable ['tmpPayment'] from the above session array.
Here are the answers. If they aren't working, be sure you're calling session_start(); before you try to modify the $_SESSION array.
$_SESSION['tmpPayment']['new_key_name'] = 'new value';
$_SESSION['tmpPayment']['item_1_amt'] = 12324;
unset($_SESSION['tmpPayment']);
1: $_SESSION["tmpPayment"]["newVariable"] = "value";
2: $_SESSION["tmpPayment"]["amount"] = "$1.78";
3: To do this, you can set ["tmpPayment"] to an empty array like so:
$_SESSION["tmpPayment"] = array();
or set it to null
$_SESSION["tmpPayment"] = null;
I borrowed a bit from this answer: PHP $_SESSION variable will not unset
and as that answer, and the other poster on this question mention, make sure to call session_start(); before doing anything with the session variables.

Create key => value pair array only if variables are set

I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);

PHP echo not working even though variable is captured

I am trying to work with this script and get it to echo the results for a variable called bio. The code below does work and when I run var_dump($result); I do get the array from the test table that shows the bio variable data for that record. Oddly, I just can't get that variable to echo using the code below. What am I missing here?
<?php
include "ASEngine/AS.php";
include "templates/header.php";
$userId = ASSession::get("user_id");
?>
Testing the bio variable return:
<?php
$result = $db->select("SELECT * FROM test WHERE user_id = :id", array( 'id' => $userId ));
echo $result['bio'];
?>
You are not accessing the array properly, should be
echo $result[0]['bio'];
because your dump shows an array of array array(1) { [0]=> array(3) {
The array you have given in the comments for vardump will look like this:
array(
array(
"user_id" => 2,
"interests"=>"",
"bio" => "This is my bio"
)
);
so you are trying to echo a key which is non existent in the first dimension of the array. Try the following:
echo $result[0]['bio'];

Parent array keys taking precedence

My session array looks like the following:
$_SESSION => array(
"acc"=>array(
"name"=>"Account name",
"id"=>1,
...
),
"name"=>"User name",
...
);
To clarify, please note that this is just to show the format. I am not actually setting $_SESSION to a new array. For that code, please see the end of the question.
If I dump the $_SESSION, I get just what I expect; however, if I try to reference one of the "acc" variables that has the a key that is used in the parent session array, it will give me the result stored in the session array.
For instance
$_SESSION["acc"]["name"]
This returns "User name", when it should return "Account name".
Why is this?
If I set the acc variable key to something else, like aname, e.g.
$_SESSION["acc"]["aname"]
This returns "Account name" like it should.
Session creation code:
session_start();
$acc = array(
"id"=>$accid,
"sub"=>$sub,
"name"=>$name,
"exp"=>$exp
);
$_SESSION["acc"] = $acc;
$_SESSION["admin"] = $admin;
$_SESSION["name"] = "$fname $lname";
$_SESSION["uid"] = $uid;
This appears to be a bug. After messing around with key names, I found that after changing the key names and undoing my changes to make the key names the same again, it worked, but after doing it again, it didn't.
Because $_SESSION is already an array when you write $_SESSION = array (.... You created array of array.

Categories