ThreadPeak
ThreadPeak

Reputation: 149

Using form method POST to an existing PHP array

Using the following form to POST to the same page upon clicking submit:

<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>

Top of the code then needs to call the form POST and append to existing array of URLs ($myUrls) upon refresh. At the moment it just replaces the existing array value.

    <?php 

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

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

...

Not sure what is wrong?

Upvotes: 0

Views: 1279

Answers (3)

Sudheesh.R
Sudheesh.R

Reputation: 356

Please try this,

  <?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>

Upvotes: 1

John Conde
John Conde

Reputation: 219794

If you're just trying to add the value for term2 to your array of URLs you can just append it to the end:

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

Upvotes: 1

At the moment it just replaces the existing array value.

Because you are directly assigning it to $myUrls variable like this $myUrls = array($_POST['term2']);

Do like this...

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

(or)

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

Upvotes: 1

Related Questions