提交&数组PHP

时间:2012-10-03 17:30:22

标签: php arrays add

我有一个问题。所以,我已经构建了我的PHP应用程序,其中包含两个文本字段(名字,姓氏)和一个提交按钮(如“添加联系人”)。我不使用MySQL。我用数组。我想要关注: 我第一次点击提交按钮时,我会看到我的联系人的名字和姓氏。第二次当我点击提交按钮时,我应该再次看到第一个conact和新的conact。例如:

首先点击 - 我明白了: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>

谢谢

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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>