Storing Form Data as a Session Variable

I am trying to pass a customer ID number entered into a form blank into session and it’s not working as I’d hoped.

<?php
session_start();    

echo '
    <form action="checkout.php" method="post">
    <div>
        Customer ID: <input type="text" name="customer_id" />
    </div>
    <input type="submit" name="checkout" value="Checkout" />
    </form>
    ';

    if (isset($_POST['checkout'])) { 
       $_SESSION['customer_id'] = $_POST['customer_id'];
    } 
?>

The code above doesn’t work, but the below does if I replace the if statement. I am typing the same number in the text box. Any suggestions are appreciated!

    $_SESSION['customer_id'] = 1024;

Unfortunately, we don’t know what your standard is for judging working vs not working, so that statement is useless to us. What exact symptom did you see and what result did you expect, that leads you to believe this is not working? And if code is responsible for displaying the non-working symptom you saw, you would need to post all the code needed to reproduce the problem, since it could be any line of all that code, from before what you have posted though to the end of the last line of code in a project, that’s causing the problem.

Next, post method form processing code should go above the start of your html document, which would mean it’s automatically above the form and you should not try to detect if the submit button is set, since it won’t be in some cases. Instead, test if $_SERVER['REQUEST_METHOD'] == 'POST' Also, storing raw external data in a session variable is not safe.

1 Like

A better example might be the below. I am just looking to get this one part fixed and I realize there are probably other areas of my code that need improvement, but I don’t want to lose focus. Last time I was given suggestions to improve my code I lost points when I submitted the assignment because I did work out of scope.

In the code below, I am trying to get the form user to enter in a cash dollar amount so the program can calculate change for them on rentalcomplete.php.

<?php
$page_title = 'Checkout';
session_start();
require '../includes/header.php';

if (!isset($_SESSION['id'])){
	echo 'You are not logged in!<br /><br /><a href=../Home/index.php class="buttons2">Login</a>';
	exit();
}

$cid = $_SESSION['customer_id']; 
$total = $_SESSION['total'];
$currency = "$";

require '../../mysqli_connect.php';
mysqli_autocommit($dbc, FALSE);

$q = "INSERT INTO rentals (customer_id, total, due_date) VALUES ($cid, $total, DATE_ADD(now(),interval 7 day))";
$r = mysqli_query($dbc, $q);


if (mysqli_affected_rows($dbc) == 1) {

	$rid = mysqli_insert_id($dbc);
	
	$q = "INSERT INTO rental_contents (rental_id, movie_id, quantity, price) VALUES (?, ?, ?, ?)";
	$stmt = mysqli_prepare($dbc, $q);
	mysqli_stmt_bind_param($stmt, 'iiid', $rid, $id, $qty, $price);

	$count = 1;
	$c = "UPDATE movies SET inventory = inventory - '$count' WHERE id='$id'"; 
	$i = mysqli_query($dbc, $c);	
	
	$affected = 0;
	foreach ($_SESSION['cart'] as $id => $item) {
		$qty = $item['quantity'];
		$price = $item['price'];
		mysqli_stmt_execute($stmt);
		$affected += mysqli_stmt_affected_rows($stmt);
	}

	mysqli_stmt_close($stmt);

	if ($affected == count($_SESSION['cart'])) { 
	
		mysqli_commit($dbc);
		unset($_SESSION['cart']);
		echo '
		
		<h1>Checkout</h1>
		<h2>Total: '.$currency.number_format($total, 2) .'</h2>
		<form action="rentalcomplete.php" method="post">
			Payment Type: 	<input type="radio" id="credit" name="credit" value="credit">
							<label for="credit">Credit</label>
							<input type="radio" id="cash" name="cash" value="cash">
							<label for="cash">Cash</label><br /><br />
			Card Number:    <input type="text" size="15" maxlength="16" name="cardnum"><br /><br />
			Exp Date:		<input type="month" name="expdate"><br /><br />
			CVV:			<input type="text" size="3" maxlength="3" name="cvv">
			<br /><br />
			Cash Amount:	$&nbsp<input type="text" size="7" maxlength="7" name=cashamt" value=""><br />			
			<input type="submit" name="pay" value="Pay" />		
		</form>
		';

		if (isset($_POST['pay'])) {				
			$_SESSION['cashamt'] = $_POST['cashamt'];			
		}
	
	} else { 	
		mysqli_rollback($dbc);		
		echo '<p>Error 2: The rental could not be processed due to a system error.</p>		
		<a href=index.php>View Cart</a>';
	}

} else {
	mysqli_rollback($dbc);
	echo '<p>Error 1: The rental could not be processed due to a system error.</p>		
	<a href=index.php>View Cart</a>';
}

mysqli_close($dbc);

echo '</div></div>';
require '../includes/footer.php';
?>

If I replace this part:

        if (isset($_POST['pay'])) {             
            $_SESSION['cashamt'] = $_POST['cashamt'];           
        }

with this:

$_SESSION['cashamt'] = 20;

rentalcomplete.php receives 20 from session and can process the math (to refund change) on the next page correctly (cashamt - total). Otherwise, I just see the total dollar amount as a negative number.

Example: $20 cash - $5 total = -$15. Instead, the next page displays -$5.

I did try this and saw no change, I still get -$5 on the next page.

By adding the following line of code, near the start of your file (after the session_start()), you can see what the $_POST data from the form is -

echo '<pre>'; print_r($_POST); echo '</pre>';

You will see that the name of the cashamt form field isn’t exactly cashamt. If you were doing this on a system where you can set php’s error related settings, you would also be getting a undefined index error at the …$_POST[‘cashamt’] statement to help point out the problem. The html markup of the name=’…’ attribute for that form field contains a mistake.

That the form field name, correct markup of the name attribute, and the posted code at the start of this thread is different from the current set, means that the cause of that problem is likely different from this one.

echo '<pre>'; print_r($_POST); echo '</pre>';
and 
echo '<pre>'; print_r($_SESSION); echo '</pre>';

This really helped! I had no idea I could do this and I wish I’d known some time ago. Thank you! I think I have this about resolved due to that.

Sponsor our Newsletter | Privacy Policy | Terms of Service