我有一个作业,我已经做了几天了。我一直试图将用户数据传递到一个数组中,即用户会输入他们的课程id,如cpsc340,然后它会显示它,然后在同一行,用户会输入cpsc 567左右,然后它会在原来的下面打印,等等,这是我目前为止所拥有的:
</head>
<body>
<form method= "post";>
<input type="text" name="courses[]" />
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
$courses = $_POST['courses'];
foreach( $courses as $key => $n ) {
echo $n;
}
?>
谁能帮我一下,或者至少给我点方向? 要达到您想要的效果,我建议使用会话。请记住,这些不会永久存储,所以如果您正在寻找永久的解决方案,您应该使用数据库来存储它们。
PHP不记得最后一个请求是什么,所以你需要把它存储在某个地方,因此我建议使用会话。你目前使用一个"HTML数组",但只有一个,所以它并没有真正的帮助。只需使用普通输入,并将其添加到存储在会话中的数组中。
请注意,session_start()
应该放在任何输出之前,因此只需将其放在文件的顶部。
我做了一些轻微的改变,以改善代码(检查值是否设置等)
<?php
session_start();
?>
<!-- the start of your HTML goes here -->
<form method="POST">
<input type="text" name="courses" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
if (!isset($_SESSION['courses']))
$_SESSION['courses'] = array(); // Initialize the array if it doesn't exist
$_SESSION['courses'][] = $_POST['courses']; // Add the value to our array
}
// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
echo $course."<br />";
}
}
?>
根据注释:
如果希望添加更多信息,例如名称和描述,则需要添加相应的输入并相应地更改会话数组:
<form method="POST">
<input type="text" name="courses" />
<input type="text" name="name" />
<input type="text" name="description" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
if (!isset($_SESSION['courses']))
$_SESSION['courses'] = array(); // Initialize the array if it doesn't exist
// Add the value to our array
$_SESSION['courses'][] = array("code" => $_POST['courses'],
"name" => $_POST['name'],
"description" => $_POST['description']);
}
// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
echo "Code: ".$course['code'].
", name: ".$course['name'].
", description: ".$course['description'].
"<br />";
}
}
?>
如果你想清除数组,你可以使用
unset($_SESSION['courses']);