Submit Button only saves one input box

Viewed 37

I'm trying to collect data from input boxes but the submit button only works for one text box. Is there a simple way to fix this? Code:

<?php
              
if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>

<!DOCTYPE html>
<html>
<head>
  <link rel="shortcut icon" href="/favicon.ico" />
  <title>Yeet!</title>
  <style>
    html {
        background-color: #181818;
    }
    body {
        color: lightgray;
        text-align: center;
        font-family: monospace;
    }
  </style>
</head>
<body>
  <form method="post">
    <br>
    <input type="text" name="textdata"><br>
    <br>
    <input type="text" name="textdata"><br>
    <br>
    <input type="text" name="textdata"><br>
    <br>
    <input type="text" name="textdata"><br>
    <br>
    <input type="text" name="textdata"><br>
    <input type="submit" name="submit">
  </form>
</body>
</html>

I just don't want all of my text boxes to have a submit button. Thanks in advance!

2 Answers

Every <input> should have an unique name:

<input type="text" name="textdata_a"><br>
<br>
<input type="text" name="textdata_b"><br>

$_POST will contain all those keys with the user input as value:

$textdataA = $_POST['textdata_a'];
$textdataB = $_POST['textdata_b'];

Your inputs all have the same name, which is why the browser effectively only transmits one of them.

<input type="text" name="textdata">
<input type="text" name="textdata">

Give them different names and access them this way on the PHP side:

<input type="text" name="firstline">
<input type="text" name="secondline">

And in PHP:

$_POST['firstline']; // will contain the data of the first input-element
$_POST['secondline']; // will contain the data of the secondinput-element
// and so on...

If you however need a indefinite number of input fields you can also use an array for that:

<input type="text" name="mytextdata[]">
<input type="text" name="mytextdata[]">

And in PHP:

$_POST['mytextdata']; // will contain the data of ALL the input fields as an array

You could (for example) merge them together like this:

$dataOfAllInputs = implode(PHP_EOL, $_POST['mytextdata']);

However, for such cases using a textarea HTML element might be more reasonable.

Related