Getting values out of a loop and saving them to a unique session variable each time

Hi everyone, so I have the below piece of code that I have developed, and I’m struggling to figure this out. What I need to make it do is save each clicked date seperately and uniquely so later it can be inserted into a mysql database table. I have tried using sessions, but still couldn’t figure out a way to create a unique session variable that carries that date. Bear in mind that there wont just be 10 boxes, there will be a calendar with endless days.

<style>
td{
	width:50px;
	height:50px;
	border:1px solid #ccc;
}
td.greyed-out{
	background-color:#f7f7f7;
}
</style>

<table>
<tr>
<?php

$dateArray = getdate();
$month = $dateArray['mon'];
$year = $dateArray['year'];



$daynumber = 10;
$day = 1;

;


while($day <= $daynumber) { 

$day0 = str_pad($day, 2, "0", STR_PAD_LEFT);
$date = "$year-$month-$day0"; 


	if ($date < date('Y-m-d')) {
	?>
		<td class="greyed-out">
		<?php echo $date; 

		?>
		</td>
	<?php		
	} else {
	?>
		<td>
		
			<form method="post" action="">
				<?php echo $date; ?>
				<input type="text" name="date" value="<?php echo $date; ?>" />
				<button type="submit" id="submit" name="choosedate" >+</button>
			</form>
		
		</td>
	<?php		
	}
	$day ++; 
} //while


if(isset($_POST['choosedate'])){
	echo $_POST['date'];
}


?>
</tr>
</table>

Don’t.

So you want to store a collection of the same form of thing. That sounds an awful lot like an Array, doesn’t it?

But how would I do that M_hutley? I have tried endlessly with session and I don’t know how to save the ones that have been clicked. I’m starting to think that this just isn’t possible to do.

So from the statement, you seem to be fairly new. Feel free to correct me if i’m tossing these balls too low.

If i give you the following strings:

"hello"
"time"
"to"
"play"

How do you put them into an array? Forget for a moment that you’re trying to do session stuff. Just put them into an array, that you will identify with the variable $myarray.

Now add the string "a game" to your $myarray array. Imagine you don’t already know how long the array is.

If you need a hint: The Array documentation in the manual provides several ways to create, and append to, arrays.

====

Now; $_SESSION itself is an array; but we can treat its members as though they were variables.
Set the 'dates' member of the $_SESSION array to be your array from earlier.

I’m stuck on the array documentation. In the entire list of array functions, the only that seems like it could add to an array is array_merge. Is that what you meant?

Sorry, what do you mean by ‘dates member’?

Okay… let’s try something less technical for a reference and see if it helps.

Start with

and then

$_SESSION is an Associative Array. Create an array (either Associative or Numerically Indexed), and then assign that array to the 'dates' key of the $_SESSION array.

(Which, incidentally, makes $_SESSION a multidimensional array at that point. You can find a link on the W3schools pages linked above to also define that term.)

I’m so confused by this again

Blockquote
'dates' key of the $_SESSION array

It does make sense in a way, but then i would manually have to enter every date of all time in order to make my code work forever.

$date['2019-12-03'] = "2019-12-03";
$date['2019-12-04'] = "2019-12-04";
$date['2019-12-05'] = "2019-12-05"; 

I’m really sorry m_hutley, I have gone over arrays many times and still don’t get how this is going to solve my problem.

I have progressed a bit with my code, and narrowed down the session name so i can at least use some value, but the code is going to get bloated really soon - I just don’t know how else to do this.

<?php
include 'connect.php'; 

 // $date = date('Y-m-d');
?>
<style>
td{
	width:50px;
	height:auto;
	border:1px solid #ccc;
}
td.greyed-out{
	background-color:#f7f7f7;
}

.chosen-box{
	background-color:aqua;
}
</style>

<table>
<tr>
<?php

$dateArray = getdate();
$month = $dateArray['mon'];
$year = $dateArray['year'];



$daynumber = 10;
$day = 1;

;


while($day <= $daynumber) { 

$day0 = str_pad($day, 2, "0", STR_PAD_LEFT);
$date = "$year-$month-$day0"; 


	if ($date < date('Y-m-d')) {
	?>
		<td class="greyed-out">
		<?php echo $date; 

		?>
		</td>
	<?php		
	} else {
	?>
		<td class="<?php if ($_SESSION['12-4'] == $month.'-'.$day) { echo 'chosen-box'; } ?>">
		
			<form method="post" action="">
				<?php echo $date; ?>
				<input type="text" name="day" value="<?php echo $day; ?>" />
				<input type="text" name="month" value="<?php echo $month; ?>" />
				<input type="text" name="date" value="<?php echo $date; ?>" />
				<button type="submit" id="submit" name="chosenDate" >+</button>
			</form>
		
		</td>
	<?php		
	}
	$day ++; 
} //while


if(isset($_POST['chosenDate']) && $_POST['month'] == 12){
	echo $_POST['date'];
	
	
	if($_POST['day'] == 3) {
		echo 'the date is 3 <br />';
		echo $_SESSION['12-3'] = $_POST['month'].'-'. $_POST['day'];
	}
	
	if($_POST['day'] == 4) {
		echo 'the date is 4 <br />';
		echo $_SESSION['12-4'] = $_POST['month'].'-'. $_POST['day'];
	}	
	
	
}


?>
</tr>
</table>

The part of the php array documentation that you should look at is the -‘Creating/modifying with square bracket syntax’. This will allow you to append the submitted dates to an array. The only value that your form should submit is the full Y-m-d chosen date (using a hidden field.) This will avoid ambiguity should anyone need to select dates that span more than a single month.

BTW - your $date value only works because you are testing during a month that has two digits in it. Your current code won’t work for months 1 - 9. You would need to insure that any date value has leading zeros for single digit values for both the month and day parts.

Variable and first-level $_SESSION associative array index names should indicate the meaning/purpose of the data in the variable. Your session index name should be something like ‘dates’ or ‘choosen_dates’ (for those that prefer underscores over camelCase.)

Your post method form processing code should be located above the start of the html document, since it is creating/modifying data on the server. You would then use the contents of the session variable at the appropriate point in the html document.

I have read and reread this and I don’t see how it ‘appends’.

Blockquote
Creating/modifying with square bracket syntax’. This will allow you to append the submitted dates to an array.

I get what you mean about the date numbers 1-9 not having the leading zero.
I cannot put the form anywhere else as each form refers to the specific number that it is on and is being generated within the while loop and the user needs to click on the box to send it.

Can no one offer up some code? I am really battling to understand everyone’s textual suggestions. I still have no clue how to add new session variables using an array. i have no idea how to implement anything like that into my code above. I have tried for 2 days now. I know I’m just not gonna get it without some extreme help at this point.

This is my progress. It kind of works, but hopefully I don’t hit a snag. I managed to work out the form code into a for loop, which i am very happy about. I still don’t know how to get the elseif statements into a for loop.
I honestly don’t know how to do the array route that has been suggested above. It doesn’t make sense to me at all.

<?php
include 'connect.php'; 

 // $date = date('Y-m-d');
?>
<style>
td{
	width:50px;
	height:auto;
	border:1px solid #ccc;
}
td.greyed-out{
	background-color:#f7f7f7;
}

.chosen-box{
	background-color:aqua;
}
</style>

<table>
<tr>
<?php

$dateArray = getdate();
$month = $dateArray['mon'];
$year = $dateArray['year'];



$daynumber = 10;
$day = 1;

;


while($day <= $daynumber) { 

$day0 = str_pad($day, 2, "0", STR_PAD_LEFT);
$date = "$year-$month-$day0"; 


	if ($date < date('Y-m-d')) {
	?>
		<td class="greyed-out">
		<?php echo $date; 

		?>
		</td>
	<?php		
	} else {
	?>
		<td class="<?php 
			if ($_SESSION['12-3'] == $month.'-'.$day) { echo 'chosen-box'; }  
			elseif($_SESSION['12-4'] == $month.'-'.$day) { echo 'chosen-box'; }
			elseif($_SESSION['12-5'] == $month.'-'.$day) { echo 'chosen-box'; }
			elseif($_SESSION['12-6'] == $month.'-'.$day) { echo 'chosen-box'; }
			elseif($_SESSION['12-7'] == $month.'-'.$day) { echo 'chosen-box'; }
			elseif($_SESSION['12-8'] == $month.'-'.$day) { echo 'chosen-box'; }
			elseif($_SESSION['12-9'] == $month.'-'.$day) { echo 'chosen-box'; }

			?>">
		
			<form method="post" action="">
				<?php echo $date; ?>
				<input type="text" name="day" value="<?php echo $day; ?>" />
				<input type="text" name="month" value="<?php echo $month; ?>" />
				<input type="text" name="date" value="<?php echo $date; ?>" />
				<button type="submit" id="submit" name="chosenDate" >+</button>
			</form>
		
		</td>
	<?php		
	}
	$day ++; 
} //while

?>



</tr>
</table>


<?php


if(isset($_POST['chosenDate']) && $_POST['month'] == 12){
	echo $_POST['date'];
	
	for($x = 1; $x <= 31; $x++) {
		if($_POST['day'] == $x) {
			echo $_SESSION['12-'.$x] = $_POST['month'].'-'. $_POST['day'];
		}
	}
	
	$page_url = $_SERVER['REQUEST_URI'];
	header('refresh:0; url='.$page_url);	
}




	for($x = 1; $x <= 31; $x++) {
		if(isset($_SESSION['12-'.$x])) {
			echo $_SESSION['12-'.$x].'<br />';
		}
	}
	
	
	


if(isset($_POST['destroy'])) {
	session_unset(); 
	$page_url = $_SERVER['REQUEST_URI'];
	header('refresh:0; url='.$page_url);	
}
?>



<form method="post" action="">
	<input type="submit" name="destroy" value="destroy" />
</form>

I am actually started to be convinced that what I am trying to do actually cannot be done.

$dates = array();
$dates[] = "2019-12-02";
$dates[] = "2019-12-03";
var_dump($dates);

This is how square-bracket syntax appends to an array.

If you’re just storing dates where something has been selected, for example a booking for that date, you could use the date as the array index.

$dates[$dayselected] = true;

and that way you’d have an array, indexed by date, containing elements just for those dates that you’ve added. You could then assign that array to a session variable, if you wanted to. (In that code, $dayselected is the date value from your form, whether the user typed it in or picked it from a date-picker.)

I can’t see why that alters where you put the form-processing code within your script.

That’s very unlikely, it’s just a case of figuring out how.

Out of interest, why don’t you want to put it into a database table straight away, even if it’s stored as “pending”?

I stated that the post method form processing code should be above the start of the html document. Not the form code.

You don’t. If you find yourself writing out repeated logic that only differs in a value it operates on, it is a sign you are doing this the hardest way possible. You are not using the computer as a tool to accomplish a task.

Your goal is to record/remember a submitted set of one or more dates. Arrays are for sets of things. For the moment, we will leave handling duplicates out of the problem. The session storage part of the post method form processing code needs to create an array that looks like -

$_SESSION['dates'][] = some submitted full date Y-m-d;
$_SESSION['dates'][] = some other submitted full date Y-m-d;

At its simplest, the code to do that would be -
$_SESSION['dates'][] = $_POST['date'];

After the end of the form processing code, $_SESSION[‘dates’] is an array that will contain the submitted dates. You can use in_array() to find out if any particular date exists in the array.

1 Like

Blockquote
Out of interest, why don’t you want to put it into a database table straight away, even if it’s stored as “pending”?

The above is exactly what I have now done - thank you for this very simple, but excellent suggestion.
Thank you to everyone else who helped me to learn alot about arrays today!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.