使用表单方法POST到现有的PHP数组

时间:2013-12-24 03:55:14

标签: php html arrays forms

点击提交时,使用以下表单发布到同一页面:

<form action="" method="post"><a class="buttonnohover">
Enter URL: </a><input type="text" name="term2" class="buttonnohover"/>
<input type="submit" class="button" name="submit" value="Add URL" />
</form>

然后,代码顶部需要调用表单POST并在刷新时追加到现有的URL数组($myUrls)。目前它只是替换现有的数组值。

    <?php 

    try 
    {
        //URLs Array
        $myUrls = array($_POST['term2']);

        //Array Push for $myUrls
        array_push($myUrls,$term2);

...

不确定是什么问题?

3 个答案:

答案 0 :(得分:1)

  

目前它只是替换现有的数组值。

因为您直接将其分配给$myUrls变量$myUrls = array($_POST['term2']);

这样做......

$term2 = array($_POST['term2']); // assign it to the $term2 variable instead of $myUrls
array_push($myUrls,$term2);

(或)

array_push($myUrls,array($_POST['term2']));

答案 1 :(得分:1)

如果您只是想将term2的值添加到您的网址数组中,您只需将其附加到最后:

$myUrls = array(); // This will normally be populated with your values
$myUrls[] = $_POST['term2'];

答案 2 :(得分:1)

请试试这个,

  <?php

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

          @session_start();

          $myUrl = array($_POST['term2']);

          // DEFINE A SESSION ARRAY [CHECK BEFORE EXISTED OR NOT}]
          $_SESSION['myUrls'] =count($_SESSION['myUrls'])>0?$_SESSION['myUrls']:array();

          //ADDED TO SESSION ARRAY
          array_push($_SESSION['myUrls'],$myUrl);

          //GET ARRAY FROM SESSION
          $myUrls = $_SESSION['myUrls'];

          //PRINT THE RESULTS
          print_r($myUrls);

   }



  ?>

  <form action="" method="post"><a class="buttonnohover">
  Enter URL: </a><input type="text" name="term2" class="buttonnohover"/>
  <input type="submit" class="button" name="submit" value="Add URL" />
  </form>