I'm doing this task in school where I'm to do something with arrays and loops in PHP.
What I've done so far is make this piece of code, that makes an array with names from a separate text-file, and chooses a random name from that array.
What I'd like it to do now is to display x amount of random names. The amount of names can be chosen in an input field, preferably with a for or while loop (those are the ones I know somewhat).
Here is my code (Don't think the text-file is necessary. If it is, just let me know):
<form method="POST">
How many names do you need?
<input type="number" name="amount" min="1" max="28"><br><br>
<input type="submit" name="proceed" value="Get name(s)">
</form>
<?php
$text = file_get_contents("names2t.txt");
$Array = explode("\n", $text);
$randNameNum = array_rand($Array);
$randPhrase = $Array[$randNameNum];
if (isset($_POST["proceed"])){
echo $randPhrase;
}
?>
Is it possible to do what I'm asking?
Just add another field on your form and loop on it :
<form method="POST">
How many names do you need? <input type="number" name="amount" min="1" max="28"><br>
How many times? <input type="number" name="repeat-count"><br>
<input type="submit" name="proceed" value="Get name(s)">
</form>
<?php
if(isset($_POST['proceed'])) {
for($i = 0; $i < $_POST['repeat-count']; $i++) {
$text = file_get_contents("names2t.txt");
$Array = explode("\n", $text);
$randNameNum = array_rand($Array);
echo $Array[$randNameNum];
}
}
?>
Related
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.
<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:
$no = array();
for($i=1; $i<=5; $i++){
array_push($no, $_POST['number']);
}
Also
$no = array();
for($i=1; $i<=5; $i++){
//$no[$i]= $_POST['number'];
}
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.
I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.
Attempt 1: This shows what I want to achieve. The same array but different key and value pair.When printed, it list out all the keys and values.
<?php
$rental[]=array('day'=>1,'rate'=>10);
$rental[]=array('day'=>2,'rate'=>20);
$rental[]=array('day'=>3,'rate'=>30);
$rental[]=array('day'=>4,'rate'=>40);
print_r($rental);
?>
Attempt 2: Now, I'm using a single form to submit multiple times.I expect the key and values to be stored inside an array each time the form is submitted. But what happens is, the last value pair overwrites the previous one.Therefore only one pair is shown. So far, I can store them with the help of session. But I just wonder if there's a way to achieve it via php array on the same page?
<?php
$rental[]=array('day'=>$_POST['days'],'rate'=>$_POST['rental']);
print_r($rental);
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['days']) && isset($_POST['rental'])){
$_SESSION['info'][] = array($_POST['days'] => $_POST['rental']);
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $days => $rental){
echo '<p>' . $days . '<br>';
echo $rental . '</p>';
}
}
}
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php
I'm making a todo list and I've got everything working except for this one thing. I need to loop over inputs that's been submitted via a form, these inputs have the same name so what I've done is storing them as an array. Now I need to loop over them so I can send them into the database one by one. Here's what I tried:
if (isset($_POST['submit'])) {
$labelValues = $_POST['labelValue[]'];
$i = 0;
while($i < sizeof($labelValues)) {
$stmt = $db->prepare("INSERT INTO tenta_table (text) VALUES (:text)");
$stmt->bindParam(':text', $labelValues[$i]);
$stmt->execute();
$i++;
}
}
HTML, the inputs are marked with red:
But it doesn't seem to work, it's not giving me any errors so I have nothing to go on. Where am I going wrong here?
Your $_POST['labelValue'] will already be an array if you have named your inputs correctly, something like <input type="text" name="labelValue[]" /> would create and array called labelValue in your POST.
From there you should be able to use your current code with one minor change
if (isset($_POST['submit'])) {
$labelValues = $_POST['labelValue'];
$i = 0;
while($i < sizeof($labelValues)) {
$stmt = $db->prepare("INSERT INTO tenta_table (text) VALUES (:text)");
$stmt->bindParam(':text', $labelValues[$i]);
$stmt->execute();
$i++;
}
}
Above I have change $labelValues to equal $_POST['lableValue'] rather than $_POST['labelValue[]']
In your case only the last input element will be available.
If you want multiple inputs with the same name use name="foo[]" for the input name attribute. $_POST will then contain an array for foo with all values from the input elements.
<form method="post">
<input name="a[]" value="foo"/>
<input name="a[]" value="bar"/>
<input name="a[]" value="baz"/>
<input type="submit" />
</form>
The reason why $_POST will only contain the last value if you don't use [] is because PHP will basically just explode and foreach over the raw query string to populate $_POST. When it encounters a name/value pair that already exists, it will overwrite the previous one.
However, you can still access the raw query string like this:
$rawQueryString = file_get_contents('php://input'))
Assuming you have a form like this:
<form method="post">
<input type="hidden" name="a" value="foo"/>
<input type="hidden" name="a" value="bar"/>
<input type="hidden" name="a" value="baz"/>
<input type="submit" />
</form>
the $rawQueryString will then contain a=foo&a=bar&a=baz.
You can then use your own logic to parse this into an array. A naive approach would be
$post = array();
foreach (explode('&', file_get_contents('php://input')) as $keyValuePair) {
list($key, $value) = explode('=', $keyValuePair);
$post[$key][] = $value;
}
which would then give you an array of arrays for each name in the query string.
or the best and simple approach for this
<form method="post">
<input name="a[0]" value="foo"/>
<input name="a[1]" value="bar"/>
<input name="a[2]" value="baz"/>
<input type="submit" />
</form>
You should replace
$labelValues = $_POST['labelValue[]'];
By
$labelValues = $_POST['labelValue'];
Not Sure, but as far as i remember it should be $labelValues = $_POST['labelValue']. I think your $labelValues is null and you don't even enter your loop. You should do a var_dump( $_POST ) to verify what you're working with.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to loop through dynamic form inputs and insert into an array
I have a php script and a form. The php script makes an xml file but what i need is for someone to enter a number and that would set that amount of textboxes that would be for someone to write data for that xml file.
So i need it to write <input type="text" name="a #"> however many times the user enters. Also the name needs to be a number but it counts by one ex:<input type="text" name="1"> <input type="text" name="2">... Thanks
<?php
session_start();
if(isset($_POST['quantity']){
// code here to check isnum and min/max
$count = $_POST['quantity'];
for ($i=1; $i<=$count; $i++){
#$s.= "<input type=text name=".$i."><br>";
}
?>
now just echo out $s in your html
This?
<form method="get" action="">
<div><input type="text" name="num_inputs" value="1" placeholder="Number of inputs"/></div>
</form>
<?php $num_inputs = isset($_GET['num_inputs']) ? $_GET['num_inputs'] : 1; ?>
<form method="post" action="">
<?php for ($i = 0; $i < $num_inputs; $i++) : ?>
<div><input type="text" name="inputs[]"/></div>
<?php endfor ?>
</form>
Edit: yes, an array is much better than input_x. Updated my answer.
I think what you want is an array of form fields.
You want something like this:
<?php
$number_of_textboxes = 5; // you'd get this from a $_GET parameter
echo str_repeat('<input type="text" name="mybox[]" />', $number_of_textboxes);
?>
This will print five text boxes:
<input type="text" name="mybox[]" />
Then, when you reference these boxes' values, you do so like thus:
<?php
foreach ($_POST['mybox'] as $i) {
echo $i;
}
?>
That is, by using "mybox[]" as the name of each input field, you create an array of textboxes, which you can then iterate through.