1

我有一个问题。所以,我用两个文本字段(名字、姓氏)和一个提交按钮(如“添加联系人”)构建了我的 PHP 应用程序。我不使用 MySQL。我使用数组。我想要以下内容:当我第一次单击提交按钮时,我应该看到我的联系人的名字和姓氏。第二次单击提交按钮时,我应该再次看到第一个联系人和新联系人。例子:

第一次点击 - 我明白了:John Johnson

第二次点击 - 我明白了:John Johnson(旧联系人)、Peter Peterson(新联系人)

她的是我的代码:

   <?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Contact {

    private $lastname;
    private $firstname;

    public function getLastname() {
        return $this->lastname;
    }

    public function setLastname($lastname) {
        $this->lastname = $lastname;
    }

    public function getFirstname() {
        return $this->firstname;
    }

    public function setFirstname($firstname) {
        $this->firstname = $firstname;
    }

}

?>



   <?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Controller {

    private $arr;

    public static function addContact($person) {
        $this->arr[] = $person;
    }

    public function getArr() {
        return $this->arr;
    }

    public function setArr($arr) {
        $this->arr = $arr;
    }

}
?>

    <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <form action="" name="form" method="post">
            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input type="text" name="fname" value=""></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input type="text" name="lname" value=""></td>
                </tr>
                <tr>
                    <td><input type="submit" name="submit" value="Add Person"></td>
                </tr>
            </table>
        </form>

        <?php
        include_once 'Contact.php';
        include_once 'Controller.php';

        $controller = new Controller();



        if (isset($_POST['submit'])) {

            $person = new Contact();
            $person->setFirstname($_POST['fname']);
            $person->setLastname($_POST['lname']);
            $controller->addContact($person);

            print_r($controller->getArr());
        }
        ?>
    </body>
</html>

谢谢

4

2 回答 2

2

您需要启动一个会话并将数组添加到 $_SESSION 数组:

http://www.thesitewizard.com/php/sessions.shtml

但请注意,只要当前会话存在,数据就会存在。

于 2012-10-03T17:32:30.947 回答
1

如前所述,您可以将会话用作存储,但它只会持续到会话超时(默认为 30 分钟)。

<?php
session_start();
 if (!isset($_SESSION['names']) || $_SERVER['REQUEST_METHOD'] == 'GET')
    $_SESSION['names'] = array();
if (!empty($_POST)) {
  $_SESSION['names'][] = $_POST['name'];
} 
?>

<?php foreach($_SESSION['names'] as $name): ?>
  <?php echo $name ?>
<?php endforeach; ?>
<form method="post">
  <input type="text" name="name" />
  <input type="submit" value="Add" />
</form>
于 2012-10-03T17:41:14.753 回答