我正在尝试创建一个基本的html表单,将信息传递给php对象,然后将所述对象添加到数组中。它的工作原理是将信息从表单传递到对象,然后将其添加到数组并显示所述对象。但是,当我尝试向数组添加第二个对象时,它似乎只是用一个新的单个元素数组替换该数组而不是添加它。这是我的代码...任何想法?
index.php文件:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
include_once 'clientInfo.php';
include_once 'clientList.php';
if ($_POST) {
$clientArray[] = new clientInfo($_POST["Fname"], $_POST["Lname"]);
}
if (!empty($clientArray)) {
$clientList = new clientList($clientArray);
}
?>
<p><a href="clientList.php">go to client list</a></p>
</body>
</html>
clintInfo.php文件:
<?php
class clientInfo {
private$Fname;
private$Lname;
public function clientInfo($F, $L) {
$this->Fname = $F;
$this->Lname = $L;
}
public function __toString() {
return $this->Fname . " " . $this->Lname;
}
}
?>
clientList.php文件:
<?php
class clientList {
public function clientList($array) {
foreach($array as $c) {
echo $c;
}
}
}
?>
带答案的编辑工作代码
index.php文件:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
if ($_POST) {
$testClient = new clientInfo($_POST["Fname"], $_POST["Lname"]);
echo $testClient . " was successfully made. <br/>";
$_SESSION['clients'][] = $testClient;
echo end($_SESSION['clients']) . " was added.";
}
?>
<p><a href="clientList.php">go to client list</a></p>
</body>
</html>
clientList.php文件:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
Accessing session variables
</title>
</head>
<body>
<h1>
Content Page
</h1>
<?php
for ($i = 0; $i < sizeof($_SESSION['clients']); $i++) {
echo $_SESSION['clients'][$i] . " was added. <br/>";
}
?>
<p><a href="index.php">return to add data</a></p>
</body>
</html>
目标文件clientInfo.php保持不变。对象需要存储在多维$ _SESSION数组中并使用for循环调用,foreach循环不起作用,除非其他人知道使foreach循环工作的方法,坚持使用for。另外,$ testClient变量可以被跳过,只是同时创建并放在$ _SESSION中,但是使用temp变量可以更容易地解决问题并看看如何使其工作。我以为我会用Josh提供的答案发布工作代码!
答案 0 :(得分:3)
您需要为数组对象添加持久性。
请参阅PHP的$_SESSION。
如果不在请求之间将其存储到内存或磁盘,则在连续加载时不可能存在。该链接中有一个很好的教程可以让你启动并运行。
或者,您可以将数据存储在数据库中,以满足更大的需求。