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) )
...
Related
I would like to have a form that enables a user to choose the vehicles. The user should get the total price of his choice. I wrote this little script, and it works properly. I am just curious is there a better way to do it. For example, there are a lot of IFs in foreach loop. What if I have, for instance, 100 checkboxes. Should I automate that in a way that for every new type of vehicle the script should make new IF statement? That sounds awkward. Is there a way to put a number of prices directly in checkbox form or something? However, what would be the best way to do such a thing. Thanx.
if (isset($_POST['submit'])){
$automobils=$_POST['auto'];
$set= array();
echo "You ordered: " ;
foreach ($automobils as $model){
if ($model == "chevrolet"){
$set[]=20000;
}
if ($model == "reno"){
$set[]=15000;
}
if ($model == "punto"){
$set[]=10000;
}
echo "<i>$model </i>";
}
$sum = array_sum($set);
echo "</br> Whole price is $sum $";
}
?>
<form action="" method="post">
<input type="checkbox" name="auto[]" value="chevrolet"/> Chevrolet</br>
<input type="checkbox" name="auto[]" value="reno"/> Reno</br>
<input type="checkbox" name="auto[]" value="punto"/> Punto</br>
<input type="submit" name="submit" value="Submit"/>
</form>
Well without adding a database and a whole another level of fun programming.
You can do this with an explode command (And really shrinks your foreach as well)
on the input value
value="chevrolet"
Change to something like
value="chevrolet;20000"
then in your foreach loop
foreach ($automobils as $model){
$eachmodel = explode(";",$model);
$set[] = $eachmodel[1];
}
Ideally you'd store your possible values, and their corresponding prices, in a database, rather than in your code. But here's a quick solution, involving an associative array acting as a map between each vehicle and its price.
$map = [
'chevrolet' => 20000,
'reno' => 15000,
'punto' => 10000
];
if (!empty($_POST['auto']) {
echo 'You ordered:<br />';
$total = 0;
foreach($_POST['auto'] as $model)
if (array_key_exists($model, $map)) {
echo ' - '.$model.'<br />';
$total += $map[$model];
}
echo 'Total price: '.$total.'<br />';
}
Then, you just update the map as you add/change vehicles/prices etc.
Note it's key to store the allowed values/prices code-side (or in a DB) rather than in your form as the latter is editable via the DOM, so you'd need something server-side to validate it anyway.
If you want to put number in checkbox. You can put it with value by using some special separator.
For example
<input type="checkbox" name="auto[]" value="punto_20000"/> Punto</br>
Later you can use Explode string and can get value for selected.
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
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.
I want to generate some HTML code (a form with several text inputs, actually) with a for loop.
I´ve tried two ways (with and without an array).
After the expected output appears into the screen, I try to view it using the browser´s "page source" utility, but even when the html code shows up into the screen it won´t show up into the page source.
WHY?
After filling the form inputs created with the for loop, I then try to get the information using $_POST, but nothing actually prints out... Maybe because of the same reason it won´t appear at the page source?
ie. typing this produces nothing: echo $_POST['fmes1'];
This is my first try:
$numOrder=1;
$mes=1;
$anio=1;
for ($i=0; $i<$cantMeses; $i++) {
$celdas = array(
$i => 'Mes <input name="fmes'.$mes.' class="ancho-celda2">
Año <input name="fanio'.$anio.' class="ancho-celda">',
);
foreach ($celdas as $elemento) {
echo $numOrder.' '.$elemento.'<br>';
}
$numOrder=$numOrder+1;
$mes=$mes+1;
$anio=$anio+1;
}
And this is my second try, not using an array:
for ($i=0; $i<$cantMeses; $i++) {
echo "<br><b>".$numOrder. "º </b>
Mes <input name='fmes".$mes." class='ancho-celda2'>
Año <input name='fanio".$anio." class='ancho-celda'>
";
}
$numOrder=$numOrder+1;
$mes=$mes+1;
$anio=$anio+1;
This is the form on calculadora.php:
<form onsubmit='return validar()' name="generar-tabla" action="calcular.php" method="POST">
Calcular intereses hasta:
Mes <?php echo '<b>'.$tMonth.'</b>';?>
Año <?php echo '<b>'.$tYear.'</b>';?>
<br>Con tasa de Interés del <input value='<?php echo $interes;?>' type='text' name='interes' class="ancho-celda">% mensual
<br>Cuántos meses se adeudan? <input type='text' name='cantMeses' class="ancho-celda" value="<?php echo $cantMeses;?>">
<br><input type='submit' name='submit' value='Generar tabla para cálculo'>
</form>
And it goes to calcular.php:
(it is still very much empty, because I´m trying to get the information form the other form. I´cve tried using the same file too)
session_start();
include ('calculadora.php');
echo $_POST['fmes1'];
In the first code snippet, I can't see where are you closing the for loop. Besides, you are resetting the $celdas contents in each loop, when you should instead append to the array.
$numOrder=1;
$mes=1;
$anio=1;
$celdas = array();
for ($i=0; $i<$cantMeses; $i++) {
$celdas[$i] = 'Mes <input name="fmes'.$mes.' class="ancho-celda2"> Año <input name="fanio'.$anio.' class="ancho-celda">';
}
foreach ($celdas as $elemento) {
echo $numOrder.' '.$elemento.'<br>';
}
Anyway, I don't see why you need to perform a loop at all. The even if $cantMeses was set somewhere else, the contents of each $celda array element doesn't seem to depend on the month index. Perhaps the $mes variable should instead be the one to iterate? Something like
$numOrder=1;
$anio=1;
$celdas = array();
for ($mes=1; $mes<=$cantMeses; $mes++) {
$celdas[$mes] = 'Mes <input name="fmes'.$mes.' class="ancho-celda2"> Año <input name="fanio'.$anio.' class="ancho-celda">';
}
foreach ($celdas as $mes=>$elemento) {
echo $mes.': '.$numOrder.' '.$elemento.'<br>';
}
This is just a wild guess.
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