I have a simple input field that takes a string "First Name Last Name" and when the user hits the submit button "Add Name", it should display what was just entered by the user in a textarea that is right below it, but also keep the previous entries until a reset button has been pressed.
I am trying to construct a loop of sorts to allow the user to keep entering names until the "Clear Names" button is pressed, but the request never finishes and times out. I feel like something like this is the solution, so is there something I am overlooking, or am I way off track?
function addName:
<?php
class AddNames {
function addName() {
$nameField = $_POST['nameField'];
if (isset($_POST['addName'])) {
do {
$arr = explode(" ", $nameField);
array_push($arr);
sort($arr);
}
while (!isset($_POST['clearNames']));
}
return "$nameFieldn";
}
}
?>
code above HTML header in index.php:
<?php
$output = "";
if(count($_POST) > 0) {
require_once 'AddNames.php';
$addName = new AddNames();
$output = $addName->addName();
}
?>
HTML body:
<body>
<div class="container">
<form method="post" action="#">
<h1>Add Names</h1>
<input class="btn btn-primary" type="submit" name="addName" value="Add Name">
<input class="btn btn-primary" type="submit" name="clearNames" value="Clear Names">
<div class="mb-3">
<label for="nameField" class="form-label">Enter Name</label>
<input type="text" class="form-control" id="nameField" name="nameField" placeholder="First & Last Name">
</div>
<label for="listOfNames">List of Names</label>
<div class="form-floating">
<textarea class="form-control" id="listOfNames" name="listOfNames" style="height: 500px">
<?php echo $output; ?>
</textarea>
</div>
</form>
</div>
</body>
2
Answers
I ended up solving my problem. I decided to rename my variables to make it more clear as to what I was doing, and that really helped. This is my solution to the AddNames class
Consider the following changes to your Class function.
It appears you are expecting a String and not an Array of Strings. This is why you chould not need a
do, while
loop.In your code, it’s not clear what you do with
$arr
, yet I suspect you mean to sort it and then combine it back into a String.