php新手。如何在单击提交按钮时保留数组的值?这个项目是这样运作的。用户将输入姓名和座位号(1-25之间),当用户单击提交按钮时,该姓名将被添加到数组中并将显示在表中。它适用于第一次输入,但当我输入另一个姓名和座位号时,第一次输入被删除。请帮助。
//this is where the user will input...
Student Name: <input type="text" name="name" id="name"><br>
Seat Number: <input type="text" name="seat" id="seat"><br>
<input type="submit" name="assign" value="Assign"> <?php echo $warning; ?>
//and this is my php code.
<?php
$students = array_fill(0, 25, NULL);//this is to make an empty array with the size of 25.
if(isset($_POST['assign'])){
$student = $_POST['name'];
$seat = $_POST['seat'];
if($seat > 25 || $seat < 1){
$warning = 'Seat number does not exist.';
}
else{
$warning = '';
$students[$seat-1] = $student;
}
}
?>
//This code here is just a part of the HTML code for the table. this is where the name will display.
<td id="box"><?php echo $students[0]; ?></td>
<td id="box"><?php echo $students[1]; ?></td>
<td id="box"><?php echo $students[2]; ?></td>
<td id="box"><?php echo $students[3]; ?></td>
<td id="box"><?php echo $students[4]; ?></td>
因为每次单击提交按钮时,$students数组都会一次又一次地创建,因此您会丢失$students所持有的先前值。因此,在第一次提交表单时只创建一次数组。
EDIT: alternative:使用php SESSION for this(只是众多选项中的一个)
在您可以在PHP会话中存储用户信息之前,您必须首先启动会话。
<?php session_start(); ?>
<html>
<body>
</body>
</html>
然后你可以通过在php中操作$_SESSION数组来存储或检索会话中的任何内容。所以,与其存储座位号。在普通的php变量中,你可以使用$_SESSION。只是保持一切相同(即方法="post"等),而不是$students使用$_SESSION["students],其中学生将是$_SESSION中的一个数组(它将保持在那里,直到你的会话过期,直到用户退出或关闭页面在你的情况下)
查看更多示例:http://www.w3schools.com/php/php_sessions.asp
这样使用会话:
<?php
session_start(); // To start the session, must be called before trying to manipulate any session variables. Preferably the first php-line on each page who will use sessions.
$_SESSION['students'] = array_fill(0, 25, NULL); // Sets an array of 25 indexes to session variable 'students'
?>
上面的代码块不应该在用户每次单击submit时都被调用——它应该只被调用一次。
<?php
session_start();
if(isset($_POST['assign'])){
$student = $_POST['name'];
$seat = $_POST['seat'];
if($seat > 25 || $seat < 1){
$warning = 'Seat number does not exist.';
}
else{
$warning = '';
$_SESSION['students'][$seat-1] = $student; // Sets index [$seat-1] of array to $student
}
}
?>
会话变量临时存储在服务器上,只要您记得在每个页面上启动会话(如代码所示),就可以在整个网站中访问会话变量。
正如Anmol之前所说,在这里阅读更多关于会话的信息:http://www.w3schools.com/php/php_sessions.asp
编辑:<?php
session_start(); // To start the session, must be called before trying to manipulate any session variables. Preferably the first php-line on each page who will use sessions.
if(!isset($_SESSION['students'])){
$_SESSION['students'] = array_fill(0, 25, NULL); // Sets an array of 25 indexes to session variable 'students'
}
?>