Hi I am trying create a system for making my own invoices, and printing them, so I created inputs with a while loop, depending on the number of articles I have entered, using the code below
<?php
$cont=1;
$numero = $_REQUEST['numeroa'];
while($cont<=$numero) {
echo $cont;
echo " <input class='Descripcion$cont' placeholder='Descripcion :' />";
echo " <input class='Precio' name='precio$cont' placeholder='Precio :' onkeyup='AddInputs()' /><br>";
$cont++;
}
echo "<textarea name='comment' >Escriba sus comentarios....</textarea>";
session_start();
$_SESSION['cont']=$cont;
?>
This sends post info to another php page, so I get something like this on the url
http://localhost/pruebas/facturapdf.php?precio1=1&precio2=2&precio3=3&precio4=4&precio5=5
I tried to get the variables using this code but I had no success
session_start();
$contp=$_SESSION['cont'];
while($cont<=$contp) {
$articulos[$cont]=$_GET['precio$cont'];
echo $articulos[$cont];
$cont++;
}
Is there a way I can use the get method changing the number each loop??
If there isn't, how can I get all the variables, knowing they are different every time, depending on the user input
thanks in advance..
As already mentioned, you're using single quotes for when you should be using double..
$articulos[$cont] = $_GET["precio$cont"];
Further, you could actually pass in an array directly as query data rather than appending a count value and looping through them.
echo " <input class='Descripcion' placeholder='Descripcion :' />";
echo " <input class='Precio' name='precio[]' placeholder='Precio :' onkeyup='AddInputs()' /><br>";
Note that I've simply changed name='precio$cont' to name='precio[]'
you can then access this as an array when submitted
$precioArr = $_GET['precio'];
Just to demostrate
for($i = 0; $i < count($precioArr); $i++) {
echo $precioArr[$i];
}
So you could actually use this for the requirements that you mentioned
If there isn't, how can I get all the variables, knowing they are different every time, depending on the user input
This can be demonstrated using this code
<?php
echo "query data:<br>";
print_r($_GET['array']);
echo "<br>";
echo "query keys:<br>";
print_r(array_keys($_GET['array']));
?>
So if you had a form like so:
<form action="demo.php" method="GET">
<input name="array[2]" type="text" value="11">
<input name="array[4]" type="text" value="11">
<input name="submit" type="submit" value="Submit">
</form>
This would pass a query query of ?array[2]=11&array[4]=11, the result you'd get is:
query data:
Array ( [2] => 11 [4] => 11 )
query keys:
Array ( [0] => 2 [1] => 4 )
try:
<?php
session_start();
$contp=$_SESSION['cont'];
while($cont<=$contp) {
$articulos[$cont]=$_GET['precio'. $cont];
echo $articulos[$cont];
$cont++;
}
difference to the original: 'precio'. $cont
this will concat the value of the variable $cont to the string literal 'precio'.
what you wrote ('precio$cont') will always be the literal string it is. no variable used.
Related
I'm trying to write a web application in which students enter their timetable. For example: First period of Monday is math, second period of Monday is English,... first period of Tuesday is history, second period of Tuesday is biology,... etc.
So I write a form like this:
<form method="post" action="timetable_handling.php">
<?php
for ($period=1;$period<=9;$period++)
{
echo "<tr>";
for ($day=1;$day<=7;$day++)
{
echo "<td><input name="the_subject_of_the_nth_$period_on_$day" type="text"></td></tr>";
//the problem is here
}
}
?>
</form>
So my question is, are there any ways to pass the many variables to another php file to handle without having to manually write its name explicitly?
Edit 1: I mean is there anyway to encode the period and day information in the name, so that when it sends to timetable_handling.php I can just loop through it to save it into sql database. Something like an array $subject[day][period].
I would be grateful if someone could help me.
Start with the following on your timetable data entry page:
<form method="post" action="timetable_handling.php">
<table>
<?php
for ($period=1; $period<=9; $period++)
{
echo '<tr>';
for ($day=1; $day<=7; $day++)
{
echo '<td><input name="subject_of_period_'.$period.'_on_day_'.$day.'" type="text"></td>';
//the problem is here
}
echo '</tr>';
}
?>
</table>
<input type="submit" value="Submit Form" />
</form>
Then follow up with this script on your timetable_handling.php:
<?php
for ($day=1; $day<=7; $day++)
{
for ($period=1; $period<=9; $period++ )
{
${'subject_of_period_'.$period.'_on_day_'.$day} = htmlspecialchars($_POST['subject_of_period_'.$period.'_on_day_'.$day],ENT_QUOTES);
echo '<p>Subject of Period '.$period.' on Day '.$day.' is '.${'subject_of_period_'.$period.'_on_day_'.$day}.'</p>';
}
}
?>
It's secure and it works.
Yes. If you format a variable name something like
for ($day=1;$day<=7;$day++)
{ ?>
<td><input name="subject['<?= $period ?>'][<?= $day ?>]" type="text"></td></tr>
//the problem is here
<?php }
PHP will turn $_POST['subject'] into a 2D array for you. (Note I make no promise this is free of syntax errors.)
In the form handler you can loop through all the posted fields like this:
foreach($_POST as $field => $value)
{
}
Where $field would be the input-tag name and $value it's value.
If you have other form elements you can check which ones you need with some kind of prefix, like if the fieldname starts with 'the_subject', you know it's one of the fields that were dynamically added.
sure, you already did part of the answer :)
first issue: you are not escaping your string properly:
Here is 1 another way
echo '<td><input name="'.$period.'_on_'.$day.'" type="text"></td></tr>';
As for handling the post here is what you can do. You might need to tweak it around to get the exact desired result. But you are talking about multidimentional array.
if (isset($_POST)){
$something=array();
foreach ($_POST as $single=>$value)
{
array_push($something, array('period_'.substr($single,0,1) => array('day_'.substr($single,-1)=>$value)));
}
}
echo '<pre>'.print_r($something,true).'</pre>';
Good Luck.
I am trying to store the values of selected checkboxes on a multi page form so I can include these on the final page of the form (and in the email that is sent to the site owner).
I have worked out how to display the values, but saving them for later has got me stumped. I'm learning as I go so I wouldn't be surprised if this is quite easy...
This is the code I'm using:
<?php foreach ($_POST['fooby'] as $key => $entry) {
if(is_array($entry)){
print $key . ": " . implode(',',$entry) . "<br>";
}
else {
print $key . ": " . $entry . "<br>";
}
} ?>
And this is the result I get:
1: Minor Service £129
2: plus MOT £35
That's exactly what I'm after - though I don't need the numbers at the beginning. How do I save that information for later?
With the updated code below, I now get the following result:
Minor Service £129
plus MOT £35
That's perfect, but I'm struggling to work out how to store that information to a session variable. I should point out that the values returned from the form are dynamic and unknown beforehand. There might also be 10 items in the array, not just the two shown above.
What I have so far:
<?php if (isset($_POST['fooby'])){
foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
$dokval = implode(',',$entry) . "<br>";
echo $dokval; //echoes the expected result on the page
$_SESSION['dokvalues'] = $dokval; //only stores the last item
}
else {
print $entry . "<br>"; //not rewritten this part yet
}
}
} ?>
Simply insert these values in hidden input elements in a form on the following pages to use them again:
<input type="hidden" name="<?php echo $key1; ?>" value="<?php echo $value1; ?>" />
<input type="hidden" name="<?php echo $key2; ?>" value="<?php echo $value2; ?>" />
...
The foreach loop iterates through the array and for each iteration $key variable is the current index and $entry is the value of that index. The numbers in the list are just representation of index values. If you don't need them, you can go for this:
<?php foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
print implode(',',$entry) . "<br>";
}
else {
print $entry . "<br>";
}
} ?>
The keys will still stay in $_POST['fooby'] array.
The variable $entry holds one value of the array each time the foreach loop iterates. So the variable $dokval will also hold only one value, which it echos each time the loop iterates. By the time you look at the session variable it's value is going to be the last value that $dokval held. Make $dokval an array and push the $entry value into it. array_push. Also, make sure you start a session at the beginning of every page you want to use the $_SESSION variable.
Jeff
I'm creating a form from a database and the input id's could be 1-9, 1,2,5,8, etc. IE with the way it is now, I cannot determine what the number will be unless I were to iterate from number 1 to the final number of menu items in the database... which I imagine is not optimal from a coding perspective.
I have two files. File1 will get list number of menu items from a database and create a list. The condensed version of my code is as follows, please keep in mind i have condensed a lot of useless stuff;
File1.php
$menuArray = openMenu(1);
$return = "<div id='menu'><form method='post' action='file2.php'><input type='submit' name='submit' value='Commit Order' /><table class='tableinfo'>";
$i=1;
foreach($menuArray as $recordNum => $record)
{
if ($record['available'] > 0)
{
$thisClass='available';
} else{
$thisClass='unavailable';
}
$return.="<tr class='$thisClass'>
<td>$record[itemid]</td>
<td><label for='$record[itemid]'>$record[name]</label></td>
<td><button type='button' id='itemid-$record[itemid]' class='subtract'>-</button><input class='itemadder' id='itemid-$record[itemid]' type='number' min='0' value='0' /><button id='itemid-$record[itemid]' class='addition' type='button'>+</button></td>
</tr>";
}
$return.="</table></form></div>";
return $return;
File2.php
I don't know how to code this :(
Is anyone able to shed some light on the best way to do this?
I just need a way to be able to see what id's have a value when posted.
I am using jQuery at the moment; would this be something best done using jquery?
Assuming I understand you correctly the best way to do this would be to have an array of inputs.
Code you should try to achieve for your HTML output would need to be something like this:
<input type="text" name="number[1]" value="" />
<input type="text" name="number[3]" value="" />
<input type="text" name="number[5]" value="" />
Now you know after your form submission in PHP:
foreach($_POST['number'] as $id => $value){
echo 'The value for ID #' . $id . ' is ' . $value;
}
The script File1.php rendering the inputs above does know about what has rendered out. So what, if it also puts a list of rendered form element names in to the session for later use in file2.php:
In the beginning:
$_SESSION['formids'] = array();
in the loop:
....
$_SESSION['formids'][] = "itemid-" . $record[itemid];
and in file2.php:
$sendItems = $_SESSION['formids'];
...
foreach ( $sendItems as $itemId )
{
$val = empty($_POST[$itemId]) ? null : $_POST[$itemId];
if ( isset($val) )
...
I've created a dynamic checkbox, but failed to display its value on another page. The work I have done is the following:
index.php
<form method="post" action="print.php">
<?php
$host="localhost";
$username="root";
$password="";
$database="checkbox";
mysql_connect($host,$username,$password);
mysql_select_db("$database");
//Create the query
$sql = "select test, rate FROM lab";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[]"value="$row['test']}/{$row['rate']}"/>
{$row['test']}-{$row['rate']}<br />
EOL;
}
?>
<br>
<input type="submit" name="submit" value="Add" />
</form>
I am trying to display the value on a secon page called print.php:
<?php
print $_POST['name'];
?>
You need to use print_r function to display all values in the array. Like
print_r($_POST['name']);
See What's happening in your code:-
You are naming your check box in array.
So when you will get the submission in php you will receive an array by the name as :- name[]
So $_POST['name'] will return an array in php.
when you use print method then it can only print variable value .
it can't print array or object . if you use print/echo method to print array/object it will just print their type.
So to print an array you can use print_r() method or you can use var_dump() to check what is in variable.
you can access array as you favourite way by any loop.
For more about print-r and var_dump please follow manual link
[php.net manual][1]
http://www.php.net/manual/en/function.var-dump.php
You will need some way for identifying which checkbox is checked. You have couple of options use and index for the variable and get it as index or identify it from the value.
Here i have added $rowNum as index for name.
$rowNum=0;
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[$rowNum]"value="$row['test']}/{$row['rate']}"/>
{$row['test']}-{$row['rate']}<br />
EOL;
$rowNum++;
}
Here if you check the first and third checkbox only, at PHP you will get
$_POST['name'] = Array
(
[0] => test0/rate0
[2] => test2/rate2
)
If you are not using the $rowNum as in your code and selecting the same options as above, you will get the folowing output.
$_POST['name'] = Array
(
[0] => test0/rate0
[1] => test2/rate2
)
You can use the array like this at print.php
if (is_array($_POST['name'])){
foreach($_POST['name'] as $key=>$name){
echo $key, '=>', $name,'<br/>';
//Here $key is the array index and $name is the value of the checkbox
}
}
I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database