Storing and retrieving $_SESSION variables - php

I've got a problem. I'm sure I'm being really stupid but I can't seem to be able to rertive a $_SESSION variable. I run throught the code with a variable called $setup which I post each time as reset. Each time I run through the code I increment $setup so it starts off with no value then has the value 1 and then then value 2. When it's one, I set a SESSION to a posted value. The next time when it's two, the SESSION doesn't seem to have a value.
This is the code when the page is loaded:
<?php
session_start();
$setup=$_POST['reset'];
if ($setup==NULL)
{
$setup=0;
}
elseif ($setup==1)
{
$_SESSION['value1']=$_POST['value1'];
$value1=$_SESSION['value1'];
}
elseif ($setup==2)
{
$value1=$_SESSION['value1'];
$_SESSION['value2']=$_POST['value2'];
$value2=$_SESSION['value2'];
}
?>
When setup is one I can print out value1 however when setup is two is use this code
echo $value2 . " " . $value1 . ".";
All I get is value2 followed by a dot. Am I doing something wrong here?

In this part of your code :
elseif ($setup==2)
{
$value1=$_SESSION['value1'];//HERE
$_SESSION['value2']=$_POST['value2'];
$value2=$_SESSION['value2'];
}
$_SESSION['value1'] is empty so $value1 will be empty too , instead of this i suggest this code:
elseif ($setup==2)
{
if(isset($_SESSION['value1']) $value1=$_SESSION['value1'];
else $value1='Some value for test';
$value2=$_SESSION['value2'];
}
ALSO:
echo $value2 . " " . $value1 ".";
Should be :
echo $value2 . " " . $value1 . ".";//if you want dot in the end
or :
echo $value2 . " " . $value1 ;//without dot int end of line

<?php
session_start();
if (!isset($_POST['reset'])) {
// do nothing or something more useful
}
else {
if ($_POST['reset'] == 1) {
$value1 = $_SESSION['value1'] = $_POST['value1'];
}
elseif ($_POST['reset'] == 2) {
$value1 = $_POST['value1']; // $_POST !!! Not $_SESSION['value1'], which is not set here!
$value2 = $_SESSION['value2'] = $_POST['value2'];
}
}
?>
$value1=$_SESSION['value1']; // you can't do this here ( == 2), because you did not set $_SESSION['value1'] to anything before

It depends on what you want to echo.
Example:
$value1 = "hello";
$value2 = "Richard";
echo $value1." ".$value2;
// will output "hello Richard" (Without the quotes)
//using your code (and syntax corrected)
echo $value1." ".$value2.".";
// will output "hello Richard." (Without the quotes)
If you want the dot to be echoed, you need to surround it with quotes "", and to break in and out of PHP vars/text etc in an echo as above.

You forgot a concatenating dot before "." string
Should be:
echo $value2 . " " . $value1 . ".";

I've fixed it. I has a reset button at the bottom to destroy the session and it had PHP in it. Maybe this question will help anyone else who make this mistake. I can happen.

Related

Concatenation & conditions in php

I'm learning PHP and i'm trying to show an " €" when and only when $autocollant_total_ht_custom isset.
This is what i wrote :
$euro = " €";
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else echo " ";
However my " €" is always showing even when $autocollant_total_ht_custom is not set.
I spent 75 minutes on it, trying and failing again and again despite researching.
I also tried with !is_null, !is_empty with the same result.
I'm fairly certain that my logic isn't wrong but the way to do it is.
Anyone to the rescue?
Have a nice Saturday everyone !
Mike.
Edit 1:
A little visual aid image
My goal was to only show the content of a cell if there was indeed something in it. By default i could see 0 in the empty cells.
if (!$autocollant_total_ht_lot10) {
$autocollant_total_ht_lot10 = " ";
} else echo "error ";
if (!$autocollant_total_ht_lot20) {
$autocollant_total_ht_lot20 = " ";
} else echo " ";
if (!$autocollant_total_ht_lot50) {
$autocollant_total_ht_lot50 = " ";
} else echo " ";
if (!$autocollant_total_ht_custom) {
$autocollant_total_ht_custom = " ";
} else echo " ";
I know my code must look primitive but it works and i don't see it making a conflict with what we are trying to achieve in the initial question.
Then, as asked, this is what i'm writing in the table row and table data :
<tr>
<td class=table_align_left>A partir de 100</td>
<td><?php echo $autocollant_prix ?></td>
<td><?php echo $autocollant_custom?></td>
<td><?php echo $autocollant_total_ht_custom?> </td>
</tr>
So in short, i'm trying to not show anything if there's no value to be shown (which is currently working) and then adding a " €" after the variable is there's something to be shown.
Edit 2 :
My primitive code : my_code
Edit 3 :
The $autocollant_total_ht_custom is already conditioned to be shown earlier in this statement :
} elseif($autocollant_quantité >= 90 && $autocollant_quantité <= 99){
$autocollant_quantité_lot50 = 2;
} elseif($autocollant_quantité >= 100 && $autocollant_quantité <= 1000){
$autocollant_custom = $autocollant_quantité;
} else echo "entrée invalide";
$autocollant_total_ht_custom = $autocollant_prix * $autocollant_custom;
$autocollant_total_ht_lot10 = $autocollant_prix_lot10 * $autocollant_quantité_lot10;
$autocollant_total_ht_lot20 = $autocollant_prix_lot20 * $autocollant_quantité_lot20;
$autocollant_total_ht_lot50 = $autocollant_prix_lot50 * $autocollant_quantité_lot50;
$pointeuse_total_ht = $pointeuse_prix * $pointeuse_quantité;
$pointeuse_autocollant_offert = $pointeuse_quantité * 10;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
I posted my code if that can help.
Mike.
//$autocollant_total_ht_custom = null;
$autocollant_total_ht_custom = "something that isnt null";
//if you switch the variable assignment above you will see it behaves as expected.
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo $autocollant_total_ht_custom = $autocollant_total_ht_custom . " " .$euro;
}
else
{
//$autocollant_total_ht_custom wouldn't be set at all if we reach this point, this is why im un-sure what your requirements are. Nothing would be echoed.
echo $autocollant_total_ht_custom;
}
Something like this maybe? It's hard to understand your exact requirements.
IsSet checks if a variable is set to something if its not null then it passes the test, and if you're manipulating strings at this variable then it will never be null, meaning the euro sign will always show up.
If the variable IS null then you fail the conditional test, hit else and echo nothing a null string.
If you can update your answer with what you would expect "$autocollant_total_ht_custom" to be set to, I can help better.
EDIT:
Seems to me you can simplify what you what, basically we are only concerned with echoing a string at all if there is something set, otherwise there's no point doing anything, so your checks could be as simple as
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo 'ht custom';
echo TDFromString($autocollant_total_ht_custom, $euro);
}
//notice this doesnt output anything because it isnt set
if (isset($autocollant_total_ht_lot10, $euro))
{
echo 'lot 10';
echo TDFromString($autocollant_total_ht_lot10, $euro);
}
//notice this does because the string, while empty is something that isnt null
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//lets set it to null and see what happens
$autocollant_total_ht_lot11 = null;
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11 AGAIN';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//it doesnt get printed!
//create a function that takes the string in question,
//and for the sake of your use case also the currency to output,
//that way you could change 'euro' to 'currency'
//and have the sign change based on what the value of the $currency
//string is, eg $currency = "£"
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Live example : https://3v4l.org/r5pKt
A more explicit example : https://3v4l.org/JtnoF
I added an extra echo to indicate (and newlines) which variable is being printed out you dont need it of course!
I'll just note the function name is a good example of a bad function name, as it not only returns a td around the string but also inserts the currency, you may want to name it a little better :)
EDIT EDIT:
A final edit outside the scope of your question, you should look into keeping your data in arrays and working on them instead.
Using the previous example we can reduce the code to just this !
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_lot12 = "2,0000000";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
//create an array, and stick all our strings in it, from now, if we need to do something to one of the strings(or all!), we do it through the array
$arrayofLots = array($autocollant_total_ht_lot10, $autocollant_total_ht_lot11, $autocollant_total_ht_lot12, $autocollant_total_ht_custom);
//go over each array 'entry' so the first time is '$autocollant_total_ht_lot10', then '$autocollant_total_ht_lot11' etc
foreach ($arrayofLots as $lot)
{
//and we've been over this bit :)
//$lot is a variable we set so we have something to refer to for the individual array entry we are on, we could just as easily name it anything else
if (isset($lot))
{
echo TDFromString($lot, $euro);
}
}
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Good day. It looks like you are missing the end brace
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else {
echo " ";
}

PHP condition fails while using Session

I made a card game with PHP but there I'm facing some issue.
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
I'm getting an input from the user. The problem is, when the game loads at first, and the user enters an input and clicks submit, the game won't work. The condition ($_SESSION["bet"] != NULL) is giving true and bankroll is not defined.
Is there a way I can set this up properly? Is there some PHP method that can initialize the variable once then only works it on session start, then the rest of the code can take care of how that variable gets updated? The bankroll variable gets initialized if the user clicks submit without anything in it right now, so the game still works but it starts improperly.
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
The bankroll variable gets initialized to 1000 every time user submits a NULL input. I want to change this.
More code... Updating...
session_start();
$_SESSION["bet"] = $_POST["bet"];
echo "<br>";
//print_r($_SESSION);
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
else if ($_SESSION["bet"] > 1000 || $_SESSION["bet"] < 0)
{
echo " Please enter between 0 and 1000.";
}
else if ($_SESSION["bet"] > $_SESSION["bankroll"])
{
echo "You can't enter more than what you have.";
}
else
{
$deck = array();
for($x = 0; $x < 54; $x++) {
$deck[$x] = $x;
}
shuffle($deck);
//Then more stuff. This one for example...
if(($houseSuits[0] == -100) || ($houseSuits[1] == -100) || ($houseSuits[2] == -100) || ($houseSuits[3] == -100))
{
echo "<br>";
echo '<center> PLAYER WINS! (HOUSE HAS JOKER) </center>';
echo "<br>";
$_SESSION["bankroll"] = $_SESSION["bankroll"] + $_SESSION["bet"]; //THESE NEED TO BE ADDRESSED.
}
I JUST WANT TO FIND A WAY TO INITIALIZE BANKROLL TO 1000 AT START. THE WAY I'M DOING IT IS BY SUBMITTING A NULL VALUE THEN ASSUMING USER NEVER SUBMITS NULL VALUE AGAIN.
I WOULD LIKE BANKROLL TO BE INITIALIZED TO 1000, THEN FOR THE GAME TO TAKE CARE OF HOW BANKROLL GETS UPDATED.
I FOUND A WAY TO DO IT BUT IT'S NOT A PROPER WAY SO THAT'S WHY I'M ASKING FOR HELP.
THANK YOU.
Ok try this.
So if the bankroll is not set, then set it, once it's set it wont get set again because it's set.
Then any conditions after are fine.
session_start();
// Initialise bankroll if not already
if (!isset($_SESSION['bankroll'])) {
$_SESSION['bankroll'] = 1000;
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
}
$_SESSION['bet'] = $_POST['bet'];
if ($_SESSION['bet'] != NULL) {
echo "Your bet is: " . $_SESSION['bet'] . "<br>";
}
if ($_SESSION['bet'] > 1000 || $_SESSION['bet'] < 0) {
echo " Please enter between 0 and 1000.";
} elseif ($_SESSION['bet'] > $_SESSION['bankroll']) {
echo "You can't enter more than what you have.";
} else {
// Your card game stuff
}
Notes: you may have issues with using session as it'll store their bet wherever they are, so issuing a bet sets the session, then navigate elsewhere and come back and their bet will still be as before. Maybe this doesn't matter.
You also might not want to check if the bet is null, more perhaps empty or whatever. Test either way to be sure.

Why can't I set a string value in this PHP code?

I visit:
http://www.mydomain.com/test.php?loc=1
This should set $location to be 'VC' and print it out to the screen.
But when I do this, I get a zero '0' instead.
What am I doing wrong, why can't I set a string?
<?php
$loc = $_REQUEST['loc'] ;
if($loc == 1){
$location = 'VC';
echo 'yes';
}
else {
echo "ERROR - Wrong Location code presented";
}
echo 'Location: ' + $location;
?>
I started with:
<?php
$loc = $_REQUEST['loc'] ;
echo 'Location: ' + $loc;
?>
Where I would visit:
http://www.mydomain.com/test.php?loc=VC
and it would do what I want, but that didn't work.
I must be missing something obvious, but I can't see what. help!
You have to change it this:
<?php
$loc = $_REQUEST['loc'] ;
echo 'Location: ' + $loc;
?>
to this:
<?php
$loc = $_REQUEST['loc'] ;
echo 'Location: ' . $loc;
?>
PHP's string concatenation operator is the . dot instead of a + as used in JavaScript, etc.
Use $_GET['loc'] instead of $_REQUEST['loc'] and concetenate with a . instead of a + as Mattedgod already stated.
Why $_GET instead of $_REQUEST?? See: Among $_REQUEST, $_GET and $_POST which one is the fastest?

if else function issue?

I have the following code with the if...else statement within a while loop.
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$nextcolr = next($colour);
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
I can't work out why what ever is in the else statement isn't being executed, even if I switch the two statements and reverse the operator. Could anyone help me?
The entire while loop:
while($row = mysql_fetch_array($result))
{
echo "by <a href='/neuro/profile.php?userid=$row[MemberID]'>" . $row['FirstName'] . " " . $row['LastName'] . "</a> on " . $row['Timestamp'] . " | " . $row['NumberOfComments'] . " comments.";
echo "<div id='blog' style='background-color:#";
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
echo "'><a href='blog.php?threadid=" . $row['tID'] . "'>" . $row['Title'] . "</a></div>";
}
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
while ... {
$nextcolr = next($colour);
if ($nextcolr === FALSE)
{
reset($colour);
}
echo current($colour);
}
is how your while loop should look like. If I am right, you are also defining $colour in the while loop, which might cause problems.
If all this is in the while loop, then you are re-declaring the array on each iteration, thus returning the array internal pointer to the beginning with each iteration.
If you want to iterate this array multiple times, you could do it this way:
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$i = 0;
while ... {
...
echo $colour[$i++ % count($colour)];
...
}
So you don't need this if-else block.
The problem with your original while loop is that you never change the value of $nextcolr.
Thus, it always remains FALSE and the else part never gets executed.

Php function in echo? Is it possible?

Hi I have a special problem ... I have three values from database.
Value1 is 1 or 0
Value2 is again 1 or 0
Value3 is remaining time like (24 hours left, 23, ...)
There values are saved in variables:
$value1
$value2
$value3
These values change from DB on every load from webpage. I have these values also inside echo""; The php function is already like:
echo"text text text .................
"Value 1 is:" . $value1 . " and value 2 is:" . $value2 . ""
..................;
I need a function that says different things like
if (value1=0)
echo "Only text"
else
echo "Value 1 is:" . $value1 . " and value 2 is:" . $value2 . "";
this to be in another echo function from first example so in my way it looks like this:
*Some function*
echo"if (value1=0)
echo "Only text"
else
echo "Value 1 is:" . $value1 . " and value 2 is:" . $value2 . """; // two echo closing
But it does not work. Any help will be appreciated.How to solve this? thank you.
Echo is saying to output whatever you type. Saying to output "echo" actually means to display the word "echo". There's no reason to output an output... you already output it!
I think what you want is something more like:
if($value1 == 0){
echo "Only text";
} else {
echo "Value 1 is:" . $value1 . " and value 2 is:" . $value2;
}
Your second piece of code looks fine. Having multiple echo statements is not a problem, and using if...else to choose one is perfectly reasonable.
If you have to use just one for some reason, you can use the (...) ? ... : ... ternary operator.
echo (value1 == 0) ? 'Only text' : "Value 1 is:" . $value1 . " and value 2 is:" . $value2 . """;
function chVal($value1, $value2) {
if ($value1 == 0) {
echo "Only text";
} else {
echo "Value 1 is:" . $value1 . " and Value 2 is:" . $value2;
}
}
Is that what you are looking for?
EDIT: I think I get what you mean.
function chVal ($val) {
if ($val == 0) {
return true;
} else {
return false;
}
}
if ($value1) {
echo "Value 1 is:" . $value1 . "\n";
} else {
echo "Only Text\n";
}
if ($value2) {
echo "Value 2 is:" . $value2 . "\n";
} else {
echo "Only Text\n";
}
Please use value1==0. Basically = means you assign the value 0 into the variable value1.
Why not use something like this:
echo "Value 1 : ".func1($value1)." - Value 2 : ".func2($value2)." - Value 3 : ".func3($value3);
then you may have 3 functions or 1 depending on how complex is your logic.
function func1($value){
if ($value == 0) return " zero ";
else return " else ";
}
Probably in this way,
echo 'if (value1=0)
echo "Only text"
else
echo "Value 1 is:"' . $value1 . " and value 2 is:" . $value2 ;
How about something like:
<?php
$value1=0;
$value2=1;
echo ($value1==0) ? "value 1 is :".$value1." and value 2 is ".$value2 : "only text";
?>
Is this what you're looking for?
I think you're looking to display the PHP code itself: http://se.php.net/manual/en/function.highlight-string.php
<?php
highlight_string('
function chkValue($value1,$value2) {
if($value1 == 0) {
echo "Only Text<br />";
} else {
echo "Value 1 is: ".$value1." and Value 2 is: ".$value2."<br />";
}
}
');
?>
It's very hard to tell what you're trying to achieve, but based on some of your other comments I'm beginning to suspect you want to echo PHP code:
$value = ($value == 0 ? 'Only Text' : "Value 1 is:$value1 and value2 is: $value2");
echo "echo \"$value\";";
update:
Yes thats it! Working but I need different colors for the two texts :-) How to add there?
I'm assuming you're outputting the text to a browser, so something like this will work:
$value = '<span style="color:#'
. ($value == 0 ? 'f00">Only Text' : "0f0\">Value 1 is: $value1 and value2 is: $value2")
. '</span>';
echo "echo \"$value\";";
echo ($value1 == 0)?'Yes':'No';

Categories