Question

I'm having a problem with my sessions forms. It's probably a simple answer but I can't seem to figure it out.

My html:

<body>
<h1>Hobby Selection Page<br /></h1>
<form method="post" action="page1.php" id="hobbies" >
<p>
   <label for="Name">Name: </label>
   <input type="text" id="name" name="name"/>
</p>
<p>What is your favorite thing to do?<br/>
<select name="hobby">
   <option value="movies">Movies</option>
   <option value="read">Reading</option>
   <option value="music">Music</option>
   <option value="other">My hobby is not listed here</option>
 </select>
 <br/><br/>
<input type="submit" value="Submit Form"/>&nbsp;<input type="reset" value="Clear Form"
/>
  </p>
  </form>
</body>

First php page (page1.php):

<?php
session_start();
echo 'Click the link below';

$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";

// Second page
echo '<br /><a href="page2.php">page 2</a>';
?>

Second php page (page2.php):

<?php
// page2.php
session_start();
echo 'Your favorite activity:<br />';

echo $_SESSION['name'];
echo $_SESSION['hobby'];

echo '<br /><a href="page1.php">page 1</a>';
?>

My aim is to input data from the first html page and then send it to the first php page (to recieve the session variables) and then to be directed to the second php page where it should retrieve the session variables and display the input data I have entered/selected. I am able to get the html and php pages to display and be linked from one page to the next but I am unable to display (in first php page) the data I have inputted from the html page.

Was it helpful?

Solution 2

In page1.php

Replace

$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";

By

$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];

OTHER TIPS

your first page1.php should be like this.

<?php
session_start();
echo 'Click the link below';

$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];;

// Second page
echo '<br /><a href="page2.php">page 2</a>';
?>

You are not getting data because you are storing string in $_SESSION not the text you entered in fields.

You're missing a few things. First give your submit button a name, like this:

<input type="submit" value="Submit Form" name="my_submit" />

Then, on page1.php, change this:

$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";

To something like this:

// Check if form was submitted. If so, get inputs.
if (isset($_POST['my_submit'])) {
   $_SESSION['name'] = $_POST['name'];
   $_SESSION['hobby'] = $_POST['hobby']; 
}

That should get you started in the right direction. Later, you can add some validation to ensure that $_POST['name'] and $_POST['hobby'] are filled in correctly before assigning them to the $_SESSION

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top