简体   繁体   中英

Form Inputs and JS

need a little help with my coding. I'm working on a project in which it will accept 5 different numbers and insert them into a PHP array. The codes I have tried are written below. Both of them would make all the 5 contents of my array the same number, appreciate a little help please? Never dealt with array in PHP yet. Sorry had to comment out the PHP since Stackoverflow is giving me error that it doesnt recognize the PHP code. Thaaanks!

 <form action="activity_1.php" method="post"> <input type="text" name="number"> <input type="submit" value="Submit" name="submit"> </form> <!-- So far these are the ones I've tried <?php $no = array(); for($i=1; $i<=5; $i++){ array_push($no, $_POST['number']); } ?> Also <?php $no = array(); for($i=1; $i<=5; $i++){ //$no[$i]= $_POST['number']; } ?> -->

enter code here

enter code here

You may use one session variable to store the posted data.

So slightly amend your code into the following :

<?php session_start(); ?>

<form action="#" method="post">

        <input type="text" name="number">
        <input type="submit" value="Submit" name="submit">
</form>



<?php
    if ( !isset($_SESSION["no"]) ) {
    $_SESSION["no"]=array();
    }

if (isset($_POST["number"])){
array_push($_SESSION["no"], $_POST['number']);
}



for($i=0; $i<5; $i++){
    if (isset($_SESSION["no"][$i])) {
       if ($_SESSION["no"][$i]!="") {
         echo " Number you entered was: " .$_SESSION["no"][$i] . "<br>";
        }
    }
}


?>

In my opinion the code can be further amended so that

a) you should have a button to "clear" all the previous entered number;

b) I don't know whether it is necessary, but you may wish to add a function to check whether a newly entered number is the same as one of the past numbers entered, and if they are the same, do not put it into the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM