Home > Blockchain >  Why does array not update when submitting form
Why does array not update when submitting form

Time:03-09

I'm currently trying to update an associative array whenever a user inputs a number and submits it via a form. All of the values of the asso array are initially set to 0 but when a number get's submitted it needs to find the the first available 0 in the array and change it to a 1. It kinda does this for the first post but when I submit the again it does not change the second 0 and outputs again the same as before (only the first key gets a 1).

Can someone explain what the logic is behind this because i'm not getting why multiple post won't update the array, or is it so that the array gets initialised on each post from the begininning with all 0's again ? If this is the case how could you go around this ? Would be the use of $_Session variable be an idea to use between two pages ?

<!DOCTYPE html>
<html>
<head>
    <title>
        Parking interface
    </title>
</head>

<body>
    <h1>test!</h1>
    <h3>test </h3>
    <form action="test1.php" method="POST">

        <input type="number" name="test" id="test">
        <label for="test">number</label><br>
        <br>
        <input type="submit" value="test">
    </form>

</body>

</html>

<?php
session_start();
$parking = array(
    "spot1" => 0, "spot2" => 0, "spot3" => 0, "spot4" => 0, "spot5" => 0,
    "spot6" => 0, "spot7" => 0, "spot8" => 0, "spot9" => 0, "spot10" => 0
);

if (!isset($_POST["test"])) {
    //echo "choose an option to continue.";
    return false;
} else {
    foreach ($parking as $key => $value) {
        if ($value === 0) {
            $parking[$key] = 1;
            break;
        }
    }
}
foreach ($parking as $key => $value) {
    echo $key . " " . $value . " ";
}
?>

Any help is more than welcome !

CodePudding user response:

Each time you make an HTTP request to the PHP URL you run the program.

At the start of the program you assign a new array to $parking with all the values set to 0.

If you want the data to persist between calls instead of resetting then you need to store the data somewhere outside of the program.

That might be in the $_SESSION (note that session_start(); has to be called at the start of the program before you output anything at all) if you want each visitor to have their own set of data for the duration of their visit or in a database (if you want the data to persist longer or be shared between users).

Then you need to pull the data from the store instead of reinitialising it from your predefined array each time.

  • Related