I tried to word the question as best as I could. I'm trying to create a web app that lists a few animals and then allows the user to add more to the list. That part is working just fine, however, I need the list to keep growing. What's happening right now is every time I put in a new input, the last one is overwritten.
For example, if I add "Tiger Shark" first and then add "Dolphin", "Tiger Shark" is completely replaced by "Dolphin" instead of "Dolphin" listing beneath "Tiger Shark". How do I prevent this from happening and ensure that each user input is listed beneath the previous one?
Edited for clarification, if needed: I'm doing this via an HTML form.
Here's my PHP code:
<?php
$animal = array("Killer Whale", "Great White Shark", "Eel");
if (isset($_POST['add']))
{
$add = array($_POST['animal']);
$animal = array_merge($animal, $add);
}
foreach($animal as $a){
echo "<li>$a</li>";
}
?>
And here is my HTML Form code:
<form method="post" action="Yarbrough_Chapter6Project.php" class="form">
<div class="form__group">
<input type="text" name="animal" class="form__input" placeholder="Favorite Sea Animal">
<label for="animal" class="form__label">Favorite Sea Animal</label>
</div>
<div class="form__group">
<input type="submit" name="add" class="btn btn--blue" value="Add An Animal">
</div>
</form>
You can just add the element to the array using [].
$animal[] = new_element will always add the new_element to the end of the array.
<?php
$animal = array("Killer Whale", "Great White Shark", "Eel");
if (isset($_POST['add']))
{
$add = $_POST['animal'];
$animal [] = $add;
}
foreach($animal as $a){
echo "<li>$a</li>";
}
?>
Related
I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['names']=array();
$names=$_SESSION['names'];
$name=$_POST['name'];
array_push($names,$name);
for($i=0;$i<count($names);$i++){
echo $names[$i];
}
};
How could i achieve to display every element inside the array that i add trough the input field in php?
You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
session_start();
if (isset($_POST['submit'])) {
if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
$_SESSION['names'] = array();
}
$name = $_POST['name'];
$_SESSION['names'][] = $name;
$num_names = count($_SESSION['names']);
for($i=0;$i<$num_names;$i++){
echo $_SESSION['names'][$i];
}
};
I am trying to make a random tournament generator, where I can select names from a list with checkboxes and then randominze them into a different order.
I have the following form:
<form method="post" action="<?php echo ROOT ?>HomeController/createTournament/" enctype="multipart/form-data">
<div class="form-group">
<label for="participants">Select participants</label><br>
<?php foreach($players as $p): ?>
<input type="checkbox" name="participants" value="<?php echo $p['name'];?>"> <?php echo $p['name'];?><br>
<?php endforeach; ?>
</div>
<button type="submit" class="btn btn-primary btn-block" name="create">Show participants</button>
</form>
This form show's a checkbox and behind the checkbox the name of the participant.
This is my method:
public function createTournament() {
if(isset($_POST["create"])) {
$participants = $_POST['participants'];
}
include('app/views/showTournament.php');
}
That means I am saving the checked ones into $participants, right?
In the file showTournament, I know have access to $partipants.
I try to var_dump $particpants and it shows me:
string(6) "Onlyoneselected name"
So I tried a foreach, to get ALL of the selected names.
<?php
foreach($participants as $p) {
echo $p;
}
;?>
The foreach isn't showing anything, but the file has access to $participants. I want all the names on my screen, so I can start randomizing them. What do I do wrong?
<input type="checkbox" name="participants"
This line here is the root of your problems.
Because every checkbox has the same name, the value of $_POST['participants'] gets overridden for each checkbox in the list.
If you change that snippet to:
<input type="checkbox" name="participants[]"
Then $_POST['participants'] becomes an array of all checked values.
You need multiple checkbox values.
And therefore, HTML name of the input should be multiple (array)
<input type="checkbox" name="participants" will return string, only latest submitted value.
<input type="checkbox" name="participants[]" will return array of all submitted values.
So, replacing name="participants" to name="participants[]" will work.
I am working on creating a PHP file and one thing that I'd like to do is have an array (Example 1). From what I understand, and Array is like a list, and I want to also input items on the list (Example 2). But the number of items in the array need to be determined by a number, inputted via a HTML form (Example 3).
Example 1:
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
</body>
</html>
</code>
Example 2:
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green");
array_push($a,"$_POST["color3"]","$_POST["color4"]");
print_r($a);
?>
</body>
</html>
Example 3.
<ol>
<form action="finished.php" method="post">
<li><input type="text" name="color3"></li>
<li><input type="text" name="color4"></li>
</form>
</ol>
EDIT:
I hope this is all formatted correctly, and you understand the question.
To reiterate: The first page is blank with just a form; single input box, where you type in any number ( X ).
The Second page has the same line repeated over and over (depending on the number X from the previous page), it's line is:
<li><input type="text" name="color Y"></li>
Y should count from 1 up infinitely until X is reached.
The Last page prints it all in a list (array?).
For Example: On the first page we enter the number 3.
On the second page we have 3 boxes for inputting the names of our chosen colors: Red, Blue, Yellow.
On the last page we are shown a list of our three colors: Red, blue and yellow.
Hope this helps.
<ol>
<form action="finished.php" method="post">
<li><input type="text" name="data['color3']"></li>
<li><input type="text" name="data['color4']"></li>
</form>
</ol>
then in the finished.php
$_POST['data'];
print_r($_POST);//print out the whole post
print_r($_POST['data']); //print out only the data array
I think I got it what you want (after reading more than once). Let me know if I understood correctly. Let's assume you're using 3 different files (as you wrote in your question).
file1.php (a simple form with 1 input and 1 submit button):
<form action="file2.php" method="post">
<input type="text" name="amount" placeholder="The amount of elements">
<input type="submit" value="Enter">
</form>
file2.php (check if $_POST and the value is an integer):
if (!empty($_POST['amount'])) {
if (!is_int($_POST['amount'])) {
exit('Not an integer');
}
?>
<form action="file3.php" method="post">
<?php
for ($i = 0; $i < $_POST['amount']; $i++) {
echo '<input type="text" name="colors[]" placeholder="Enter color name"><br>';
}
?>
<input type="submit" value="Done">
</form>
<?php
} else {
exit('Only $_POST method is allowed.');
}
file3.php (get all results and store an array in variable):
if (!empty($_POST)) {
$colors = $_POST['colors'];
foreach ($colors as $color => $value) {
echo '<li>'.$value.'</li>';
}
exit;
} else {
exit('Only $_POST method is allowed.');
}
We can add some more security (like checking if it's not empty, etc.), but I'm adding just basic things.
I have a button on a page that when a user pushes it, it creates another "Contact" field on the page. The Contact field allows them to add a new contact to their profile. Also, they can click the button as many times as they want, and it will create that many "Contact" fields.
The problem though is that I am having a hard time figuring how many "Contact" fileds have been added. Here is some HTML that is generated when the button is clicked:
<div class="item">
<label for="in-1v">First Name <span>*</span></label>
<div class="text">
<input type="text" id="in-1-0" name="member[0][fname]" value="" />
</div>
</div>
<div class="item">
<label for="in-2-0">Last Name <span>*</span></label>
<div class="text">
<input type="text" id="in-2-0" name="member[0][lname]" value="" />
</div>
</div>
Each time the button is clicked, name="member[0][lname]" will become name="member[1][lname]" and will continue to increment each time the button is clicked. As stated earlier, the user can do this as many times as they want on the page.
I am using PHP to loop through the multidimensional array:
$array = $_POST['member'] ;
foreach($array as $array_element) {
$fname = $array_element['fname'];
$lname = $array_element['lname'];
}
How can I use PHP to determine how many fileds have been added so I can loop through them?
Any help is greatly appreciated!
You can simply get a count like so:
$count = count($_POST['member']);
You could also then modify your loop to look like this:
// First check to see if member is set and is a valid array
if (!empty($_POST['member']) && is_array($_POST['member'])) {
$count = count($_POST['member']);
for ($i = 0; $i < $count; $i++) {
$fname = $_POST['member'][$i]['fname'];
$lname = $_POST['member'][$i]['lname'];
}
}
Im trying to make a html form processed in php that outputs to pdf and is print ready.
This is what I have:
A page requesting the categories to include
A page which presents text areas for that categories
A page which displays the final result with an option to print and or make a pdf.
I can make all the information pass along the pages what im lacking is way to display the content properly formatted.
I need this layout:
Text here bold: Description of item
Description of item
(precisely one empty line)
Some more bold text: Description of item
Description of item
and so on.
Im a bit stumbled since the Item descriptions are coming from text areas of which I am able to preserve the line breaks by echoing <.pre> (please excuse the dot, i dont understand how to escape the tag ;) tags along, which end up including all the white space due to the textarea cols.
Assuming I have two textareas and two variables with the titles posting to the last page, how would i go about formatting it properly?
Thank you.
-----EDIT-------
To clarify what I intend:
I have 3 pages:
1 one:
<div class="menu">
Por favor seleccione os conteúdos:
<form name="Categorias" action="Elementos_Descritivos.php" method="post">
<div class="cb-row">
<label for="nome">Nome:</label>
<input id="nome" name="Nome" type="checkbox" value="Nome" checked />
</div>
<div class="cb-row">
<label for="data">Data:</label>
<input id="data" name="Data" type="checkbox" value="Data" checked />
</div>
<div class="cb-row">
<label for="cliente">Cliente:</label>
<input id="cliente" name="Cliente" type="checkbox" value="Cliente" checked />
</div>
<div class="cb-row">
<label for="ob">Observações:</label>
<input id="ob" name="Observacoes" type="checkbox" value="Observacoes" checked />
</div>
<div class="submit">
<input type="submit" value="Seguinte" />
</div>
</form>
</div>
</div>
In this one you choose wich categories go into the doc.
Page 2:
<body>
<?php
$Nome = $_POST["Nome"];
$Data = $_POST["Data"];
$Cliente = $_POST["Cliente"];
$Observacoes = $_POST["Observacoes"];
$Nome1 = "Nome";
$Data1 = "Data";
$Cliente1 = "Cliente";
$Observacoes1 = "Observacoes";
echo "<div class=\"menu2\">
<form name=\"Detalhes\" action=\"Pre_Impressao.php\" method=\"post\">
Por favor preencha os todos os campos em branco:<br/><br/>";
#######################################_NOME_######################################
if ( $Nome == $Nome1 ) {
echo "<div> Nome: <textarea name=\"Nome\" rows=\"6\" cols=\"60\"></textarea></div> <br/>";
}
########################################_DATA_#####################################
if ( $Data == $Data1 ) {
echo "<div> Data: <textarea name=\"Data\" rows=\"6\" cols=\"60\"></textarea></div><br/>";
}
########################################_CLIENTE_##################################
if ( $Cliente == $Cliente1 ) {
echo "<div> Cliente: <textarea name=\"Cliente\" rows=\"6\" cols=\"60\"></textarea></div> <br/>";
}
#######################################_OBSERVACOES_###############################
if ( $Observacoes == $Observacoes1 ) {
echo "<div> Observacoes: <textarea name=\"Observacoes\" rows=\"6\" cols=\"60\"></textarea></div><br/>";
}
####################################################################################
echo "<div class=\"submit\">
<input type=\"submit\" value=\"Seguinte\" />
</div>
</form>
</div>
?>
The second page displays text areas for filling information about hte categories selected in the previous page.
And then page 3, which ought to display the inputs nicely formatted, that's were im stumbled, I know my php is hideous, and i would be better off with a for each loop but for now im trying to focus on getting it done rather than getting it done in a better way :)
If im still not being clear in any aspect please let me clarify so i can improve the post.
Thanks.
You can put PHP code inside normal HTML code (or PDF code), but it might be easier to iterate and generate this way:
If I remember correctly, you can put your data in a table and the formatting will render properly in a PDF. I have also come across the issue that some CSS properties do not render properly in PDF. Hope that helps.