craigie2204
craigie2204

Reputation: 361

Form Input to Session Variable

First question I have is that I would like on the index.php to ask the user a question via a form and when the press submit it updates the session variable on jcart.php. With the current code below when I call the session variable later on it is now found so I assume the code I have just now is not working correctly.

The second question is when I press submit it takes me to jcart.php is there a way to avoid this or have it go back.

On my index.php I have a form :

<form action="jcart/jcart.php" method="post">
<input type="text" name="example" id="example" />
<input type="submit" name="submit" value="Submit" />
</form>

And on Jcart.php :

$_SESSION['example'] = $_POST['example'];

Then on the page I am calling it on cocktails.php

<?php 
include_once('jcart/jcart.php');
session_start();
?>

<input type="hidden" name="my-item-id" value="<?php echo $_SESSION['example'];?>" />

Thanks for your help.

Upvotes: 1

Views: 5800

Answers (3)

Nisam
Nisam

Reputation: 2285

Please try this

*jcart.php*

session_start();
$_SESSION['example'] = $_POST['example'];

*then cocktails.php*

include_once('jcart/jcart.php');

echo $_SESSION['example'];

Upvotes: 1

Petros Mastrantonas
Petros Mastrantonas

Reputation: 1046

in jcart/jcart.php

session_start();

should be called at the beginning

Upvotes: 0

mpratt
mpratt

Reputation: 1608

There is no need to "update the session variable on jcart.php". Once you store a data into the global $_SESSION array, it should be available on all php files, at least until you destroy the session.

That being said, if jcart/jcart.php needs to have a $_SESSION['example'] variable, you need to be sure, that the session is started before including the file, for instance:

<?php 
    session_start()
    include_once('jcart/jcart.php');
?>

For your other question, you can change the action inside your form to whatever you like or issue a header('Location: /'); to redirect to other page after the value was recieved.

Upvotes: 2

Related Questions