Reputation: 7
I want to add form data into an array using session.
How can I do this please help me.
My HTML form is:
<form action="#" method="post">
Roll No:<input type="text" name="rollno" value="" id="rollno" />
<input type="submit" name="submit" value="Submit" />
</form>
And my PHP code is:
<?php
session_start();
$_SESSION['rollno'] = isset($_POST['rollno']);
echo $_SESSION['rollno'];
?>
I want to insert roll no into an array.
I have a record of 10 students. When I am inserting the first student Roll No then it prints the roll no, but when I insert the second student Roll No it overwrites the first student record.
I want to display all 10 student roll nos on same page.
How can I do this?
Upvotes: 0
Views: 3625
Reputation: 5658
$_SESSION['rollno']
should be an array not a simple variable.
Something like this:
<?php
//Define somewhere $_SESSION['rollno'] as array. ONLY ONCE. Note that session must be started.
session_start();
if (!isset($_SESSION['rollno'])){
$_SESSION['rollno'] = array();
}
if(isset($_POST['rollno'])){
array_push($_SESSION['rollno'],$_POST['rollno']);
}
foreach ($_SESSION['rollno'] as $item){
echo $item;
}
?>
Upvotes: 1
Reputation: 26281
Almost there
<?php
session_start();
!isset($_SESSION['rollno']){$_SESSION['rollno']=array();}
$_SESSION['rollno'][] = $_POST['rollno'];
?>
Also, recommend setting action to something:
echo("<form action={$_SERVER['PHP_SELF']} method='post'>");
Some don't like to use PHP_SELF and recommend hard coding it
Upvotes: 0
Reputation: 62
i know !
Let's try :
<?php
session_start();
$_SESSION['rollno'] = Array();
$_SESSION['rollno'][] = $_POST['rollno'];
$_SESSION['rollno'][] = $_POST['rollno'];
var_dump($_SESSION['rollno']);
?>
You can access it from loop too .. Good luck
Upvotes: 0
Reputation: 7055
session_start();
if(isset($_POST['submit'])){
if(isset($_POST['rollno'])){
$_SESSION['rollno'] = $_POST['rollno'];
echo $_SESSION['rollno'];
}
}
Check first if form is submitted, then roll is set and if yes, assign it to session var.
Upvotes: 0
Reputation: 32740
Start the session before you out put any thing to the page, ie before html code
Make session a multi dimensional array
Remove isset
from isset($_POST['rollno']);
<?php
session_start();
$_SESSION['rollno'][] = $_POST['rollno'];
print_r($_SESSION['rollno']);
?>
Upvotes: 2